我一直在尝试网页中的元编程,并且需要在运行另一个脚本标记之后延迟脚本标记的运行直到 。但是,需要首先加载脚本标记,否则它们都将失败。
我尝试做的缩短且更具可读性的版本:
<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
属性失败,因为按钮是在第一个脚本标记运行之前加载的,否则这将非常有效。
提前谢谢!
答案 0 :(得分:1)
正如@meagar在评论中所建议的,如果您不介意更改“非实际javascript”脚本块的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>