Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery to load Javascript file dynamically

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?

like image 830
Jeff Meatball Yang Avatar asked Oct 15 '22 06:10

Jeff Meatball Yang


People also ask

What is getScript?

The getScript() method is used to get and execute a JavaScript using an AJAX HTTP GET request.

How to load a JavaScript file dynamically?

Load JavaScript files dynamically 1 Loading JavaScript dynamically. A <script> element can be created and appended to the DOM just like any other HTML element. ... 2 Determining when a JavaScript file is loaded. The real challenge isn’t loading the file – it’s knowing when the file has finished loading. ... 3 Dueling with dinosaurs. ...

How do I load a JavaScript script into an HTML page?

1 - You can load it with an AJAX call then use eval. This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks. 2 - Add a script element with the script URL in the HTML. Definitely the best way to go.

How do I load a JavaScript file in a GET request?

For example, to load a Javascript file at /javascript/myscript.js do this: If you need to execute some additional code after the Javascript file is loaded then do this: Note that this makes a GET request and if POST is required then you need to use the $.ajax () function directly, as shown below, instead of the $.getScript () shorthand.

What is the best way to get a script from jQuery?

If you have jQuery loaded already, you should use $.getScript. This has an advantage over the other answers here in that you have a built in callback function (to guarantee the script is loaded before the dependant code runs) and you can control caching. Show activity on this post.


2 Answers

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

like image 205
Paolo Bergantino Avatar answered Oct 16 '22 19:10

Paolo Bergantino


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
});
like image 24
dana Avatar answered Oct 16 '22 19:10

dana