简体   繁体   English

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

[英]execute script on load of current script

I want to do something like document.currentScript.onload = function(){alert(0)}; 我想做类似document.currentScript.onload = function(){alert(0)};事情document.currentScript.onload = function(){alert(0)}; . Basically, executing some code after the current script is done executing. 基本上,在当前脚本执行完毕后执行一些代码。 How would you do that? 你会怎么做?

Note that this is an inline script. 请注意,这是一个内联脚本。 I want to set the onload handler only under certain conditions that can be known during the execution of current script only. 我只想在某些条件下设置onload处理程序,这些条件只能在当前脚本的执行过程中知道。

What I have tried: 我尝试过的

  1. The snippet above. 上面的代码段。 This did not work and my guess is that you cannot set an onload handler on a currently executing script. 这没有用,我的猜测是您不能在当前执行的脚本上设置onload处理程序。 My reasoning may be wrong though. 我的推理可能是错误的。
  2. document.write('\\x3cscript>alert(0);\\x3c/script>'); . My hope was that the content of document.write would execute after the current script has finished execution. 我希望可以在当前脚本执行完后执行document.write的内容。 However, it seems that the content is executing as soon as it is written on the page stream. 但是,似乎内容一被写入页面流就立即执行。

The load event is fired only for external scripts ( your code would work if it was inside an external script ). 仅对外部脚本触发load事件( 如果代码 在外部脚本中,则 代码将起作用 )。

A Firefox only solution is to use the afterscriptexecute event. 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> 


Other than these, i can only think ( as suggested in the comments ) to use an empty callback which is overridden with your code if your conditions are met. 除此之外,我只能认为( 如注释中所建议 )使用一个空的回调,如果满足您的条件,则该回调将被您的代码覆盖。

Something like 就像是

 <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> 

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

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