Situation: I send an ajax request that returns HTML containing elements needing event handlers to be set on them. The code that sets the handlers for these elements is contained in a separate javascript file.
I have been using the following code to load the required js files on callback by scripting the <head> tag. I have not had problems so far, but was wondering if this is a safe and reliable approach (especially cross-browser).
function ajax_callback(response) {
document.getElementById('dom_id_to_update').innerHTML = response;
import_js('/path/to/js/file/');
}
function import_js(src) {
var scriptElem = document.createElement('script');
scriptElem.setAttribute('src',src);
scriptElem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptElem);
}
Thanks, Brian
Yup. You can even remove the
scriptelement immediately after adding it (though you may want to keep it around to avoid re-loading later — e.g., by looking at whatscripttags are inhead); apparently just the act of adding it is all that’s required to get the code loaded and parsed. More here (that page is from the Prototype unofficial wiki, but it’s applicable regardless of whether you’re using Prototype).