0

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

2 Answers 2

1

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 — e.g., 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).

Sign up to request clarification or add additional context in comments.

Comments

1

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/

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.