How To Make Sure jQuery Is Loaded And Only Once

Posted by Ahmed Tarek Hasan on 12/26/2012 07:53:00 PM with No comments
While working with Sharepoint you will notice that adding jQuery to the main masterpage is not a good idea cause sometimes and with some jQuery versions problems happen just after adding jQuery even without using it. May be some of you encountered this problem or not but at least it happened to me and some other colleagues.

So, the first lesson here is, don't add jQuery on every page except when you really need it.

Also, when working with webparts, you may be using jQuery on more than one webpart, so you need to make sure that jQuery is added to whatever page including one of these webparts. Any page may include one or multiple of these webparts, so you can't depend on making only one of them responsible for adding jQuery to the page cause in case of absence of this webpart any jQuery code will fail.

Another thing, suppose that a page includes two webparts which require jQuery to be added to the page. One is loaded at the header of the page, lets call it "A", while the other is loaded at the footer of the same page, lets call it "B". If "A" extends jQuery object with some custom code, then "B" added jQuery again to the page, this will override the custom code introduced by "A" and jQuery will be reverted to its original source code. I am sure this is not what you really need.

So, the second lesson here, add jQuery only once to the page.

Another thing, you can add jQuery to the page using some JavaScript code which will add a "script" tag to the DOM, but you can't start using jQuery just after running this JavaScript code because jQuery library itself is not yet fully loaded.

So, the third lesson here, before firing jQuery code, you need to make sure that jQuery is fully loaded and ready to perform.


So, now before going through the practical approach to overcome all of these issues, lets summarize what we really need to achieve here.

We need to:
  1. Add jQuery to pages only when needed
  2. In case of adding jQuery to a page, make sure to add it only once
  3. Before firing any jQuery code, make sure jQuery is fully loaded


After searching for a while, I found some tips and came up with the code below.

This is a method called "RunWithJQuerySupport" which you can add to a common utilities js file. This method takes care of all the three points above.
function RunWithJQuerySupport(success) {
    if (typeof jQuery == 'undefined') {
        function getScript(success1) {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = "_layouts/1033/JS/ITWorx.UTCNow/jquery-1.8.1.min.js";
            done = false;
            script.onload = script.onreadystatechange = function () {
                if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
                    done = true;
                    if (typeof (success1) != 'undefined' && success1 != null) { success1(); }
                    script.onload = script.onreadystatechange = null;
                };
            };
            head.appendChild(script);
        };

        getScript(function () {
            if (typeof jQuery == 'undefined') {
                // Super failsafe - still somehow failed...
            } else {
                //jQuery.noConflict();
                if (typeof (success) != 'undefined' && success != null) { success(); }
            }
        });
    } else {
        if (typeof (success) != 'undefined' && success != null) { success(); }
    };
}

So, suppose that somewhere on a page or a webpart you need to call a method called "StartAjaxCall"
and you want to make sure that your call will follow the three points above. To achieve this, you can use the code below.
function StartAjaxCall(){
 alert("Ajax Call Started");
}

RunWithJQuerySupport(StartAjaxCall);

This will make sure that the three points above are followed and finally fire your method “StartAjaxCall”.

If you need to only add jQuery to the page without calling any other method, you can call "RunWithJQuerySupport" without passing any parameters as follows.
RunWithJQuerySupport();

Please note that in the "RunWithJQuerySupport" method, the url for the jQuery.js file is hard-coded on the 6th line. You can update it or even add it as a parameter to the “RunWithJQuerySupport” method to be passed with each call.


That's all, wish you find this helpful.



Categories: ,