如何延迟脚本标记,直到其他脚本标记运行

时间:2018-03-09 14:25:03

标签: javascript html metaprogramming script-tag

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

我尝试做的缩短且更具可读性的版本:

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

1 个答案:

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