Can't append [removed] element

后端 未结 18 2223
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 06:11

Any idea why the piece of code below does not add the script element to the DOM?

var code = \"\";
$(\"#someElement\").append(cod         


        
18条回答
  •  心在旅途
    2020-11-21 06:42

    You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:

    const script = "console.log('Did it work?')"
    new Promise((resolve, reject) => {
      (function(i,s,o,g,r,a,m){
          a=s.createElement(o),m=s.getElementsByTagName(o)[0];
          a.innerText=g;
          a.onload=r;m.parentNode.insertBefore(a,m)}
      )(window,document,'script',script, resolve())
    }).then(() => console.log('Sure did!'))
    

    It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.

提交回复
热议问题