How To Make Sure jQuery Is Loaded And Only Once
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.
- Add jQuery to pages only when needed
- In case of adding jQuery to a page, make sure to add it only once
- 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.
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.