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?
The getScript() method is used to get and execute a JavaScript using an AJAX HTTP GET request.
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. ...
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.
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.
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.
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 :)
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With