Sunday, 18 October 2015

Load External JS at run time in JQuery



jQuery provides a function called "getScript", which allows to load external Javascript or js file on the fly.
The advantage of using $.getScript is that it loads the content on run time, which is far better than including <script> tag in your head section. jQuery getScript load a JavaScript file from the server using a GET HTTP request, then execute it. The syntax of $.getScript is,
$.getScript('url', callback function(){
    //call the function here....
});

·         url: A string containing the URL to which the request is sent. It will be URL of your JS file.
·         callback function: A callback function that is executed if the request succeeds.
$.getScript('js/jsPlugin.js', function () {
    Demo(); //This function is placed in jsPlugin.js file
});
This is a shorthand Ajax function, which is equivalent to
$.ajax({
    url: url,
    dataType: "script",
    success: success
});
But do you know what happens internally? When loading external JS file using .getScript method, what it does it that it appends a timestamp with every request. So the request may look like,
<script src="/js/jsPlugin.js?_=ts2499874935">
instead of,
<script src="/js/jsPlugin.js">
So what it does by appending timestamp is, it tells the browser to get a fresh copy of JS file every time. In other words, it disables the cache or it doesn't allow browser to cache the Js file. Which can be great sometimes but not always.

What if you want to cache the script, so that it doesn't download every time from the server?
Well, there are 2 ways. First is, before making call to $.getScript method, you can set the cache true for AJAX request and set it to false once script is loaded
.
//Set Cache to true.
$.ajaxSetup({ cache: true });
$.getScript(urlhere, function () {
    //call the function here....
    //Set cache to false.
    $.ajaxSetup({ cache: false });
});
Second solution is to modify the default implementation of $.getScript to allow cache. The default implementation of $.getScript is,
$.getScript = function (url, callback) {
    $.ajax({
        type: "GET",
        url: url,
        success: callback,
        dataType: "script"
    });
};
All you need to do is to add a boolean parameter, which will set the cache attribute to true or false. That's the beauty of jQuery that you can redefine things the way you need.
$.getScript = function (url, callback, cache) {
    $.ajax({
        type: "GET",
        url: url,
        success: callback,
        dataType: "script",
        cache: cache
    });
};
So,now you call the $.getScript like, (notice the 3rd argument)
$.getScript('js/jsPlugin.js', function () {
    Demo(); //This function is placed in jsPlugin.js file
}, true);
Don't worry, it will not break your existing code as if jQuery doesn't find the 3rd parameter then it will assign undefined or no to this attribute.


No comments:

Post a Comment