jQuery's $.getScript
function is a quick and easy way to include external JavaScript files into a website. However, its default implimentation will not cache the script file for the client.
The following information describes how you can itilize cached versions of $.getScript
- Include jquery, if it's not already.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
- Add me to the
plugins.js
file
(function($){$.getScriptCached=function(url,callback){return $.ajax({url:url,dataType:"script",cache:true}).done(callback)}})(jQuery)
- Use it in the
scripts.js
ormvscreen.js
file
$.getScriptCached('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js', function(){
console.log(moment);
});
You can also try implimenting some other versions of this idea:
-
jQuery .getScript() refactor to prevent caching
//getScript refactor to prevent caching (function () { $.getScript = function(url, callback, cache) { $.ajax({ type: "GET", url: url, success: callback, dataType: "script", cache: cache }); }; })();
Examples:
//normal no cached version $.getScript('js/script.js', function() { //do something after script loaded }); //cache = true $.getScript('js/script.js', function() { //do something after script loaded }, true);
-
https://api.jquery.com/jquery.getscript/
By default,
$.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $ .ajaxSetup():$.ajaxSetup({ cache: true });
Alternatively, you could define a new method that uses the more flexible $.ajax() method.
Examples:
Define a $.cachedScript() method that allows fetching a cached script:
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 ); });