Executing inline JavaScript when using AJAX

April 27, 2011 by aaron
Executing inline JavaScript when using AJAX

AJAX is full of stumbling blocks. From browser support to user expectations, it can cause more problems than it solves when used at the CMS level. In AJAXed WordPress, I had to find a way to enable javascript processing on arbitrary scripts from other plugins loaded with AJAX. Typically, this is impossible because most inline JS uses the document.write function to output content. Once the page is written with the updated content, document.write is dangerous and can overwrite the entire page.

Even more importantly, inline JS is never run when embedded <script> tags are used with the innerHTML command. The following JavaScript function fixes both problems by eval’ing the content of the <script> tags and replacing the default document.write with a new function that replaces the inline JS with the output of the document.write function.

The Code

function executeJS(i){ // Pass an element ID to the function.
    var e = document.getElementById(i);
    var Reg = '(?:)'; //Regex for all content between &lt;script> tags.
    var match    = new RegExp(Reg, 'img');
    var scripts  = e.innerHTML.match(match);
    var doc = document.write; // Store the functionality of document.write temporarily.
    //Overwrite document.write with a new function that takes the innerHTML of the passed element
    //then replaces the &lt;script> tag with the output of the passed content.
    document.write = function(p){ e.innerHTML = e.innerHTML.replace(scripts[s],p)};
    if(scripts) { //if matches
        for(var s = 0; s &lt; scripts.length; s++) { //loop through matches
            var js = '';
            var match = new RegExp(Reg, 'im'); //find first match
            js = scripts[s].match(match)[1]; //inner content of the first match
            eval('try{'+js+'}catch(e){}'); //evaluate the inline JS.


    document.write = doc; //Reset document.write back to its original functionality


This example function only outputs the first document.write in a script block, so if you require more than one in your embedded JS, it is trivial to store the output content as a variable.

comments powered by Disqus

Do you have an awesome idea?

Let us know what you want to create.

Start your project