Executing – JCOC611 Jan 06 '11 at 21:28

  • I added an example of using the success callback: – Christopher Tokar Jan 06 '11 at 21:32
  • 1
    Thank you so much! the "myFunction();" part was what I was leaving out of my code. – Jason Sep 25 '13 at 15:32
  • 11

    Here is the script that will evaluates all script tags in the text.

    function evalJSFromHtml(html) {
      var newElement = document.createElement('div');
      newElement.innerHTML = html;
    
      var scripts = newElement.getElementsByTagName("script");
      for (var i = 0; i < scripts.length; ++i) {
        var script = scripts[i];
        eval(script.innerHTML);
      }
    }
    

    Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

    Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

    Evgenii
    • 36,389
    • 27
    • 134
    • 170
    6

    This 'just works' for me using jQuery, provided you don't try to append a subset the XHR-returned HTML to the document. (See this bug report showing the problem with jQuery.)

    Here is an example showing it working:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
    <html lang="en"> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
        <title>test_1.4</title> 
        <script type="text/javascript" charset="utf-8" src="jquery.1.4.2.js"></script> 
        <script type="text/javascript" charset="utf-8"> 
            var snippet = "<div><span id='a'>JS did not run<\/span><script type='text/javascript'>" +
            "$('#a').html('Hooray! JS ran!');" +
            "<\/script><\/div>";
            $(function(){
                $('#replaceable').replaceWith($(snippet));
            });
        </script> 
    </head> 
    <body> 
        <div id="replaceable">I'm going away.</div> 
    </body> 
    </html>
    

    Here is the equivalent of the above: http://jsfiddle.net/2CTLH/

    Phrogz
    • 296,393
    • 112
    • 651
    • 745
    • 1
      Highly unlikely this would be the solution to the problem currently, as that was a bug with really old version of jQuery. – NoBugs Nov 08 '15 at 09:05
    3

    Here is a function you can use to parse AJAX responses, especially if you use minifiedjs and want it to execute the returned Javascript or just want to parse the scripts without adding them to the DOM, it handles exception errors as well. I used this code in php4sack library and it is useful outside of the library.

    function parseScript(_source) {
        var source = _source;
        var scripts = new Array();
    
        // Strip out tags
        while(source.toLowerCase().indexOf("<script") > -1 || source.toLowerCase().indexOf("</script") > -1) {
            var s = source.toLowerCase().indexOf("<script");
            var s_e = source.indexOf(">", s);
            var e = source.toLowerCase().indexOf("</script", s);
            var e_e = source.indexOf(">", e);
    
            // Add to scripts array
            scripts.push(source.substring(s_e+1, e));
            // Strip from source
            source = source.substring(0, s) + source.substring(e_e+1);
        }
    
        // Loop through every script collected and eval it
        for(var i=0; i<scripts.length; i++) {
            try {
              if (scripts[i] != '')
              {         
                try  {          //IE
                      execScript(scripts[i]);   
          }
          catch(ex)           //Firefox
          {
            window.eval(scripts[i]);
          }   
    
                }  
            }
            catch(e) {
                // do what you want here when a script fails
             // window.alert('Script failed to run - '+scripts[i]);
              if (e instanceof SyntaxError) console.log (e.message+' - '+scripts[i]);
                        }
        }
    // Return the cleaned source
        return source;
     }
    
    Andre Van Zuydam
    • 651
    • 7
    • 12
    2

    If you are injecting something that needs the script tag, you may get an uncaught syntax error and say illegal token. To avoid this, be sure to escape the forward slashes in your closing script tag(s). ie;

    var output += '<\/script>';
    

    Same goes for any closing tags, such as a form tag.

    TommyRay
    • 131
    • 8
    2

    This worked for me by calling eval on each script content from ajax .done :

    $.ajax({}).done(function (data) {      
        $('div#content script').each(function (index, element) { eval(element.innerHTML); 
    })  
    

    Note: I didn't write parameters to $.ajax which you have to adjust according to your ajax.

    shivgre
    • 1,163
    • 2
    • 13
    • 29
    0

    I had a similiar post here, addEventListener load on ajax load WITHOUT jquery

    How I solved it was to insert calls to functions within my stateChange function. The page I had setup was 3 buttons that would load 3 different pages into the contentArea. Because I had to know which button was being pressed to load page 1, 2 or 3, I could easily use if/else statements to determine which page is being loaded and then which function to run. What I was trying to do was register different button listeners that would only work when the specific page was loaded because of element IDs..

    so...

    if (page1 is being loaded, pageload = 1) run function registerListeners1

    then the same for page 2 or 3.

    Community
    • 1
    • 1
    Richard Chase
    • 407
    • 5
    • 21
    0

    My conclusion is HTML doesn't allows NESTED SCRIPT tags. If you are using javascript for injecting HTML code that include script tags inside is not going to work because the javascript goes in a script tag too. You can test it with the next code and you will be that it's not going to work. The use case is you are calling a service with AJAX or similar, you are getting HTML and you want to inject it in the HTML DOM straight forward. If the injected HTML code has inside SCRIPT tags is not going to work.

    <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body></body><script>document.getElementsByTagName("body")[0].innerHTML = "<script>console.log('hi there')</script>\n<div>hello world</div>\n"</script></html>
    
    Antonio Martin
    • 361
    • 3
    • 12
    0

    you can put your script inside an iframe using the srcdoc attribute example:

     <iframe frameborder="0" srcdoc="
           <script type='text/javascript'>
              func();
            </script>
      </iframe>
    
    Moukim hfaiedh
    • 409
    • 6
    • 9
    -3

    Another thing to do is to load the page with a script such as:

    <div id="content" onmouseover='myFunction();$(this).prop( 'onmouseover', null );'>
    <script type="text/javascript">
    function myFunction() {
      //do something
    }
    myFunction();
    </script>
    </div>
    

    This will load the page, then run the script and remove the event handler when the function has been run. This will not run immediately after an ajax load, but if you are waiting for the user to enter the div element, this will work just fine.

    PS. Requires Jquery

    Joshua Klein
    • 189
    • 2
    • 13