简体   繁体   中英

Load JavaScript from HTML text dynamically?

I have a modular single page html that dynamically loads content html based on a wide variety of attributes which are not important. The code below works great except the script is not loaded. I have a place in the dynamic load function to insert script but can't find any examples of this type of loading. Everything assumes an src file however I know you can do something like below with element.text but not sure how to load that from the html text.

Note that all the references I have found load via an.src and not the.text which I need.

function dynamicLoad(elem, sourceCode) {
        // load html not the issue        
        elem.innerHTML = sourceCode;
        // load JS -- this is with solution ---
        var doc = document.implementation.createHTMLDocument(); // Sandbox
        doc.body.innerHTML = sourceCode; // Parse HTML properly
 // --- This is the solution below, will load all scripts found    
        [].map.call(doc.getElementsByTagName('script'), function(el) {       
          var e = document.createElement('script');
          e.text = el.textContent;
          document.body.appendChild(e);        
        }
  }

Referring to my comment over this answer, I don't know if that is actually what you are looking for but I hope it will help!

 var loadedScript = "alert('Eval is working;')"; function evalScript() { return eval(loadedScript); }
 <button onclick="evalScript()">Eval script</button>

Answer is posted inline code above but here it is:

// Insert JS 
var doc = document.implementation.createHTMLDocument(); // Sandbox
doc.body.innerHTML = data; // Parse HTML properly
[].map.call(doc.getElementsByTagName('script'), function(el) {       
  var e = document.createElement('script');
  e.text = el.textContent;
  document.body.appendChild(e);        
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM