gpt4 book ai didi

javascript - 检查函数是否启动 javascript

转载 作者:行者123 更新时间:2023-12-03 12:25:50 25 4
gpt4 key购买 nike

有什么办法可以检查页面上是否已添加此脚本。

function init(){

var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'setTimeout(function(){ alert("test msg") }, 10000);';
document.body.appendChild(script);

}

注意: 我希望您运行一个函数,直到它不再运行为止。

最佳答案

我对标题感到困惑,如果调用该函数,您要求提供解决方案,而在您的消息中,您要求提供解决方案来检查脚本是否已存在于页面上。所以我解决了这两个问题。

1) 了解脚本何时完成加载并开始运行脚本:

function init(callback){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'setTimeout(function(){ alert("test msg") }, 10000);';
script.onload = callback;
document.body.appendChild(script);
}

init(function(e){
console.log('script loaded.',e);
});

2) 检查脚本是否已经添加到dom

function init(){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'setTimeout(function(){ alert("test msg") }, 10000);';
var checkExistance = document.scripts.filter(function(v){ return v.isEqualNode(script) });
var exists = checkExistance.length>0;
if(!exists) document.body.appendChild(script);
}

3) 如果需要的话可以组合它们...如果脚本已经存在,则不会调用回调,因为文件一旦添加到 DOM 就会开始加载。

function init(callback){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'setTimeout(function(){ alert("test msg") }, 10000);';
script.onload = callback;
var checkExistance = document.scripts.filter(function(v){ return v.isEqualNode(script) });
var exists = checkExistance.length>0;
if(!exists) document.body.appendChild(script);
}

init(function(e){
console.log('script loaded.',e);
});

关于javascript - 检查函数是否启动 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24215863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com