eval() doesn't execute external (src=…) scripts

后端 未结 2 547
遥遥无期
遥遥无期 2021-01-29 10:43

I\'m using eval() to execute all

2条回答
  •  粉色の甜心
    2021-01-29 11:00

    Here's one thing you could do:

    var html = "Some html with a script ";
    
    var frag = parsePartialHtml(html);
    
    fixScriptsSoTheyAreExecuted(frag);
    
    
    document.body.appendChild(frag);
    
    
    function fixScriptsSoTheyAreExecuted(el) {
      var scripts = el.querySelectorAll('script'),
          script, fixedScript, i, len;
    
      for (i = 0, len = scripts.length; i < len; i++) {
        script = scripts[i];
    
        fixedScript = document.createElement('script');
        fixedScript.type = script.type;
        if (script.innerHTML) fixedScript.innerHTML = script.innerHTML;
        else fixedScript.src = script.src;
        fixedScript.async = false;
    
        script.parentNode.replaceChild(fixedScript, script);
      }
    }
    
    
    function parsePartialHtml(html) {
      var doc = new DOMParser().parseFromString(html, 'text/html'),
          frag = document.createDocumentFragment(),
          childNodes = doc.body.childNodes;
    
      while (childNodes.length) frag.appendChild(childNodes[0]);
    
      return frag;
    }
    

提交回复
热议问题