JQuery to load Javascript file dynamically
Asked Answered
L

2

142

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?

Leventis answered 26/5, 2009 at 20:53 Comment(1)
This is a great fork of the TinyMCE compressor, that adds asynchronous loading of TinyMCE via the jQuery.tinyMCE plugin, and includes Gzip, concatenation and minification :github.com/bobbravo2/tinymce_compressor/blob/master/…Malena
S
206

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

Schram answered 26/5, 2009 at 20:54 Comment(2)
@Jose: Thanks :), @Jeff: No problem. As far as jQuery awesomeness goes this one is fairly unknown.Schram
TLDR; only do this if the scripts are in the same directory. Longer version: getScript actually injects the javascript into current scrips instead of the page. what this means is any paths on the included javascript will be relative to the current document.Feigned
L
24

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});
Lorolla answered 2/5, 2014 at 19:30 Comment(3)
This may not have been available when you wrote this, but note that jQuery allows you (globally) to disable this no-caching feature and allow caching again. See api.jquery.com/jQuery.getScript/#caching-requests (Oh, I see the $.ajax() approach you cover here is mentioned there as well.)Demmer
@PeterHansen - Thanks for the tip. I updated my answer with your suggestion.Lorolla
jQuery 1.12.0 or later support disabling the anticache inline like this: $.getScript({url: "test.js",cache:true})Ballard

© 2022 - 2024 — McMap. All rights reserved.