Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defer JavaScript Load to Specific Page Anchor

I have some JavaScript code that I'd like to load only once the page scrolls to a certain id tag.

For example, imagine I have a script model.js and an html element <p id='anchor'></p>.

My goal is to trigger the load of <script src="model.js"></script> at the point when the page reaches the <p id='anchor'></p>

I'm assuming there's a fairly trivial way to achieve this, but I'm having difficulty finding how how to do so. So far my research only yielded stuff using defer or async in the <script> load, but those don't seem to give me the results I want.

Any help is greatly appreciated!

like image 825
Jared Wilber Avatar asked Jul 10 '26 22:07

Jared Wilber


1 Answers

In order to solve your problem, I decided to add the script to the DOM, once the scroll position of the element was reached and then set the src attribute to model.js.

In order to only add the script once, the first time the script was added, I removed the event listener from the document.

Using jQuery:

let anchorOffsetTop = $("#anchor").offset().top;

$(document).on("scroll", function () {
  console.log(anchorOffsetTop, $(window).height(), $(this).scrollTop());
  if ($(this).scrollTop() + $(window).height() > anchorOffsetTop) {

    let s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "model.js";

    $("body").append(s); // add script to body
    $(document).off("scroll"); // remove event listener

    console.log(s);
  }
});

Using pure Vanilla JS:

let anchorOffsetTop2 = document.getElementById("anchor").offsetTop;

const addScript = () => {
  if (
    document.documentElement.scrollTop + window.innerHeight >
    anchorOffsetTop2
  ) {
    let s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "model.js";

    document.body.appendChild(s);
    console.log(s);
    window.removeEventListener("scroll", addScript);
  }
};

window.addEventListener("scroll", addScript);

See this codepen to test the code out.

like image 79
koder613 Avatar answered Jul 13 '26 21:07

koder613



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!