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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With