gpt4 book ai didi

javascript - 如何延迟脚本标签直到其他脚本标签运行

转载 作者:行者123 更新时间:2023-12-03 02:20:09 24 4
gpt4 key购买 nike

我一直在网页中尝试元编程,并且需要将脚本标记的运行延迟到恰好在另一个脚本标记运行之后。但是,需要先加载脚本标签,否则两者都会失败。

我正在尝试做的事情的简短且更易读的版本:

<script defer>
w=function(){
<stuff that gives a parser error until modified by the next script tag>
}
</script>
<script>
<stuff that changes the previous script tag and any other script tags that ever will be added via the DOM
so it doesn't give a parser error>
</script>
<button onclick='w()'></button>

这会工作得很好,除了按钮的 onclick 属性失败,因为按钮是在第一个脚本标记运行之前加载的。提前致谢!

(编辑:I linked a pastebin to show the full version of my code, it might clear things up a bit since it seems my summed-up version wasn't very good.

最佳答案

正如 @meagar 在评论中所建议的,如果您不介意更改“实际上不是 javascript”脚本 block 的 type 属性,您可以执行以下操作:

<script type='derpscript'>
var derp;
var w=function(){alert('hello')};
derp||=5;
console.log(derp);
</script>

<script>
function compileDerps() {
// find all derpscript script tags
var x = document.querySelectorAll('script[type=derpscript]');
for(var i=0;i<x.length;i++){
meta=x[i].text
while(true){
pastmeta=meta;
console.log(exc=regex.exec(meta))
if(exc){
meta=meta.replace(regex,exc[1]+'='+exc[1]+'||');
}
if(pastmeta==meta){break;}
}
// make a new javascript script tag to hold the compiled derp
var s = document.createElement('script');
s.text = meta;
document.body.appendChild(s);
// delete the derpscript tag
x[i].parentNode.removeChild(x[i]);
}
}

//stuff that changes the previous script tag and any other script tags that ever will be added via the DOM
var regex=/([a-zA-Z$_][a-zA-Z$_1-9]*)(\|\|\=)/;
var meta;
var pastmeta='';
var exc='';

compileDerps();
</script>

<button onclick='w()'>THIS IS W</button>

关于javascript - 如何延迟脚本标签直到其他脚本标签运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49195866/

24 4 0