Return to Snippet

Revision: 37715
at December 15, 2010 20:22 by madr


Initial Code
/**
 * attach_and_execute_scripts helper function
 * Copyright (c) 2010 by Anders Ytterström <http://madr.se>
 * Released under the MIT license.
 *
 * Description: 
 * A light-weight function to extract and execute SCRIPT from
 * an ajax response. it also attach the new content to the DOM
 * tree.
 */
function attach_and_execute_scripts(wrapper_elm, ajax_response, create_target) {
    var target_elm;
    var extracted_scripts;
    
    extracted_scripts = (function (tmp_elm) {
        tmp_elm.innerHTML = ajax_response;
        
        var refs = [], scr = tmp_elm.getElementsByTagName('script');
        
        for (var i = 0, max = scr.length; i < max; i++) {
            refs.push(scr[i].cloneNode(true));
        }
        
        return refs;
    })(document.createElement('div'));
    
    // will prevent Gecko from executing scripts twice
    cleaned_markup = ajax_response
    .replace(/<script[^>]*>[nsS]*?</script>/img, '');
    
    target_elm = create_target(cleaned_markup);
    wrapper_elm.appendChild(target_elm);
    
    // caution: document.write will break the page!
    if (extracted_scripts) {
        for(var i = 0, max = extracted_scripts.length; i < max; i++) {
            target_elm.appendChild(extracted_scripts[i]);
        }
    }
}

Initial URL

                                

Initial Description

                                

Initial Title
Attach ajax content and execute scripts in it

Initial Tags
ajax, javascript, textmate

Initial Language
Other