我想做document.currentScript.onload = function(){alert(0)};
之类的事情。基本上,在当前脚本完成执行后执行一些代码。你会怎么做?
请注意,这是一个内联脚本。我想只在某些条件下设置onload处理程序,这些条件只能在当前脚本的执行过程中知道。
我尝试过:
document.write('\x3cscript>alert(0);\x3c/script>');
。我希望document.write
的内容在当前脚本执行完毕后执行。但是,似乎内容在页面流上写入后立即执行。答案 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;
除了这些之外,我只能认为(,如评论中所建议的)使用空回调,如果满足您的条件,该回调会被您的代码覆盖。
像
这样的东西
<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;