简体   繁体   English

检查该功能是否已启动javascript

[英]check whether the function is launched javascript

is there any idea how I can check whether it is already added this script on the page. 有什么办法可以检查该脚本是否已经在页面上添加了吗?

function init(){

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

}

NOTE: I want you to run one function until after it no longer runs. 注意:我希望您运行一个功能,直到不再运行为止。

I got confused in the title you ask for a solution if the function is called and in you message you ask for a solution to check if the script exists already on the page. 在标题中,如果函数被调用,您要寻求解决方案;对于您的消息,您要寻求解决方案以检查脚本是否已存在于页面上,我感到困惑。 So I solved both. 所以我都解决了。

1) know when the script has completed loading and started running your 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) check if the script was already added to the dom 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) combine them if you want... The callback won't be called if the script exists already since the file starts loading as soon as it's added to the DOM. 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM