views:

31

answers:

2

Hello,

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

+1  A: 
T.J. Crowder
+1  A: 

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/

Zach Bialecki
They'd have *a* handler attached, but presumably not the *right* one. I'm assuming he has a *reason* that he has to load an external script, rather than just referencing functions in his existing script as he would with `live` (or any other form of event delegation; it's not unique to jQuery).
T.J. Crowder