JQuery to load Javascript file dynamically

Jeff Meatball Yang picture Jeff Meatball Yang · May 26, 2009 · Viewed 120k times · Source

I have a very large javascript file I would like to load only if the user clicks on a certain button. I am using jQuery as my framework. Is there a built-in method or plugin that will help me do this?

Some more detail: I have a "Add Comment" button that should load the TinyMCE javascript file (I've boiled all the TinyMCE stuff down to a single JS file), then call tinyMCE.init(...).

I don't want to load this at the initial page load because not everyone will click "Add Comment".

I understand I can just do:

$("#addComment").click(function(e) { document.write("<script...") });

but is there a better/encapsulated way?

Answer

Paolo Bergantino picture Paolo Bergantino · May 26, 2009

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)