How to change this onload function so that this script runs as soon as the button id elements are loaded on page?

Viewed 20
<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.

1 Answers

Here's example that demonstrate "right after", "domcontentloaded" and then "load" in that order.

window.addEventListener('DOMContentLoaded', function (ev) {
    console.log('DOM fully loaded and parsed');
});

window.addEventListener('load', function (ev) {
    console.log('all assets downloaded');
});
<h1>html</h1>

<button id="test" style="color:red">what color?</button>
<script>
document.querySelector("#test").style.color = 'blue';

console.log ("i am first in order of appearance")
</script>

Related