<script type="text/javascript">
window.onload = function () {
const signInBtn = document.getElementById("sign-in-btn");
appendUtmsToButton(signInBtn);
const signUpBtn = document.getElementById("sign-up-btn");
appendUtmsToButton(signUpBtn);
};
function appendUtmsToButton(button) {
// Read utm params from url:
const pageSearch = window.location.search;
const urlParams = new URLSearchParams(pageSearch);
// Build new params for the button combining the button' params with the utm:
const buttonUrl = new URL(button.href);
let newButtonParams = new URLSearchParams(buttonUrl.search);
urlParams.forEach(function(value, key) {
newButtonParams.append(key, value);
});
// Build new url for the button attaching the params:
buttonUrl.search = "";
const newSearchString = newButtonParams.toString();
buttonUrl.search = newSearchString;
const newHref = buttonUrl.toString();
// Replace the button's url:
button.href = newHref;
// For debugging log final button link to console:
// console.log(button.href);
};
</script>
This above code works well but because it is an onload function it takes a long time for it to run and the button URL's to update. I want to run this as soon as the buttons (with those ID's) are loaded on page.