[英]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.我有一些 JavaScript 代码,我只想在页面滚动到某个 id 标签时加载它们。
For example, imagine I have a script model.js
and an html element <p id='anchor'></p>
.例如,假设我有一个脚本model.js
和一个 html 元素<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>
我的目标是在页面到达<p id='anchor'></p>
时触发<script src="model.js"></script>
的加载
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.到目前为止,我的研究只产生了在<script>
加载中使用defer
或async
东西,但那些似乎并没有给我想要的结果。
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
.为了解决您的问题,我决定将脚本添加到 DOM,一旦到达元素的滚动位置,然后将src
属性设置为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
.为了只添加一次脚本,第一次添加脚本时,我从document
删除了事件监听器。
Using jQuery:使用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:使用纯香草 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.