简体   繁体   中英

Loading javascripts in ajax callbacks

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 script element immediately after adding it (though you may want to keep it around to avoid re-loading later — eg, by looking at what script tags are in head ); 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).

It doesn't look like you're using jQuery which is too bad, because there is a function, live , that specifically deals with this case. The live function attaches a handler to all elements that match the selector now and in the future. So no matter when your new elements are appended to the page the handler will be automatically attached, without you having to load new scripts.

You can see the documentation and examples here: http://api.jquery.com/live/

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