在加载当前脚本时执行脚本

时间:2017-12-20 22:18:36

标签: javascript events

我想做document.currentScript.onload = function(){alert(0)};之类的事情。基本上,在当前脚本完成执行后执行一些代码。你会怎么做?

请注意,这是一个内联脚本。我想只在某些条件下设置onload处理程序,这些条件只能在当前脚本的执行过程中知道。

我尝试过:

  1. 上面的代码段。这不起作用,我的猜测是你不能在当前正在执行的脚本上设置onload处理程序。我的理由可能是错的。
  2. document.write('\x3cscript>alert(0);\x3c/script>');。我希望document.write的内容在当前脚本执行完毕后执行。但是,似乎内容在页面流上写入后立即执行。

1 个答案:

答案 0 :(得分:0)

load事件被触发only for external scripts如果代码在外部脚本中,则代码可以正常工作)。

Firefox 解决方案是使用afterscriptexecute事件。



<script id="first">
  document.addEventListener("afterscriptexecute", function(e){
    console.log(`Script "${e.target.id}" just finished executing`);
  }, true);
</script>
<script id="second">console.log('a log');</script>
<script id="third">console.log('another log');</script>
<script id="fourth">console.log('yet another log');</script>
&#13;
&#13;
&#13;

除了这些之外,我只能认为(,如评论中所建议的)使用空回调,如果满足您的条件,该回调会被您的代码覆盖。

这样的东西

&#13;
&#13;
<script>
    let afterscriptexecute = function(){}; 
    
    // .. your code
    
    if (Math.random() < 0.5){ // if condition is met
       afterscriptexecute = function(){
         // do something
         alert('conditions were met');
       }
    }
    
    // end of your code
    
    afterscriptexecute();
</script>
    
    
&#13;
&#13;
&#13;