检查函数是否启动了javascript

时间:2014-06-14 01:41:27

标签: javascript function append

有什么想法我可以检查它是否已经在页面上添加了这个脚本。

function init(){

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

}

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

1 个答案:

答案 0 :(得分:1)

如果函数被调用,我在你要求解决方案的标题中感到困惑,并且在你的消息中你要求一个解决方案来检查脚本是否已经存在于页面上。所以我解决了两个问题。

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);
});