Checking if jquery is loaded using Javascript

JavascriptJquery

Javascript Problem Overview


I am attempting to check if my Jquery Library is loaded onto my HTML page. I am checking to see if it works, but something is not right. Here is what I have:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript" src="/query-1.6.3.min.js"></script>
        <script type="text/javascript">
          $(document).ready(function(){
             if (jQuery) {  
               // jQuery is loaded  
	           alert("Yeah!");
	         } else {
               // jQuery is not loaded
	           alert("Doesn't Work");
    	     }
          });
        </script>

Javascript Solutions


Solution 1 - Javascript

> something is not right

Well, you are using jQuery to check for the presence of jQuery. If jQuery isn't loaded then $() won't even run at all and your callback won't execute, unless you're using another library and that library happens to share the same $() syntax.

Remove your $(document).ready() (use something like window.onload instead):

window.onload = function() {
    if (window.jQuery) {  
        // jQuery is loaded  
        alert("Yeah!");
    } else {
        // jQuery is not loaded
        alert("Doesn't Work");
    }
}

Solution 2 - Javascript

As per this link:

if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}


there are a few more in comments of the link as well like,

if (typeof jQuery == 'function') {...}

//or

if (typeof $== 'function') {...}

// or

if (jQuery) {
    alert("jquery is loaded");
} else {
    alert("Not loaded");
}


Hope this covers most of the good ways to get this thing done!!

Solution 3 - Javascript

if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}

Solution 4 - Javascript

You can do this fast on the console-tab when inspecting your webpage.

E.g:

$ === jQuery

If it returns true it means it's loaded.

Solution 5 - Javascript

Just a small modification that might actually solve the problem:

window.onload = function() {
   if (window.jQuery) {  
       // jQuery is loaded  
       alert("Yeah!");
   } else {
    location.reload();
   }
}

Instead of $(document).Ready(function() use window.onload = function().

Solution 6 - Javascript

CAUTION: Do not use jQuery to test your jQuery

When you are using any of the code provided by other users and if you want to display the message on your window and not on the alert or console.log, Then make sure you use javascript and not jquery.

Not everyone want to use alert or console.log

alert('jquery is working');
console.log('jquery is working');

The code below will fail to display the message
Because we are using jquery inside the else (how the hell the message displays on your screen if you do not have jquery)

if ('undefined' == typeof window.jQuery) {
    $('#selector').appendTo('jquery is NOT working');
} else {
    $('#selector').appendTo('jquery is working');
}

Use JavaScript instead

if ('undefined' == typeof window.jQuery) {
    document.getElementById('selector').innerHTML = "jquery is NOT working";
} else {
    document.getElementById('selector').innerHTML = "jquery is working";
}

Solution 7 - Javascript

Update:

Nowadays I use this in production and it works like a charm.

Make sure that you are indeed loading jQuery though, otherwise it can cause an infinite loop. I'd recommend adding a counter & breaking it if you need:

(async() => {
    console.log("waiting for jQuery");

    while(!window.hasOwnProperty("jQuery")) {
        await new Promise(resolve => setTimeout(resolve, 100));
    }
       
    console.log("jQuery is loaded.");
})();

Old answer: You can check whether it exists and, if it does not exist, load it dynamically.

function loadScript(src) {
    return new Promise(function (resolve, reject) {
        var s;
        s = document.createElement('script');
        s.src = src;
        s.onload = resolve;
        s.onerror = reject;
        document.head.appendChild(s);
    });
}



async function load(){
if (!window.jQuery){
    await loadScript(`https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js`);
}

console.log(jQuery);

}

load();

Solution 8 - Javascript

If jQuery is loading asynchronously, you can wait till it is defined, checking for it every period of time:

(function() {
    var a = setInterval( function() {
        if ( typeof window.jQuery === 'undefined' ) {
            return;
        }
        clearInterval( a );

        console.log( 'jQuery is loaded' ); // call your function with jQuery instead of this
    }, 500 );
})();

This method can be used for any variable, you are waiting to appear.

Solution 9 - Javascript

Below is a Universal Cross-Browser JQuery Loader. This one checks if the document's DOM, HTML, CSS, files and resources are fully loaded, and if the JQuery file itself was parsed and running. This checker works in older browsers and supports old Internet Explorer (v. 4-11) as well as various user agents going back to 2001. It is limited only by various versions of JQuery itself that happen to be bug free in those browsers. Sadly, many are not.

Keep in mind, you cannot run scripts that rely on JQuery till the JQuery files and any resources used are downloaded, parsed, and JIT compiled. You can also use the code below to test if DOM is processed early in the browser before other resources are downloaded, and run non-JQuery early scripts to work with the DOM. The first function below demonstrates that feature. This assumes only the DOM is built and many CSS, images, and JavaScript files are still not downloaded. This is useful if you need deferred scripts to download early before JQuery and other libraries and manipulate the DOM for some reason.

    // EARLY JAVASCRIPT DOM PROCESSING (non-JQuery)
    // Function to run as soon as the HTML is parsed and DOM rendered.
    function DOMStart(state) {
        if (state == null) {
            state = "Unknown";
        }
        alert('DOM State: ' + state);
    };

    // FULLY LOADED WINDOW/DOCUMENT JAVASCRIPT PROCESSING, plus JQUERY CHECK
    // TEST IF JQUERY IS LOADED (without using JQuery)
    // Function to run as soon as all resources associated with the document are ready and JQuery script files are loaded.

    function JQueryStart(state) {
        if (state == null) {
            state = "Unknown";
        }
        alert('JQuery State: ' + state);

        //if (typeof window.jQuery !== 'undefined') { // Alt. Version #2 check
        if (window.jQuery) {
            // jquery is loaded...
            alert("JQuery is loaded.");

            // JQuery is downloaded. Now use JQuery to test if
            // the document object model is fully
            // loaded again from the point of view of JQuery.
            // In most cases it is based on logic below.
            // It is possible to load this function only when the
            // DOM is ready instead of the whole document and all
            // its files are ready and run a timer to detect when 
            // "window.jQuery" above is true. That would allow you
            // to know JQuery is downloaded prior to the DOM and 
            // utilize it earlier.

            $(document).ready(function () {

                // ======== Begin JQuery Scripts ======== 


            });
        } else {
            // JQuery did not load...
            console.log("JQuery failed to load!");
            alert("JQuery failed to load!");
        }
    };


    // OLD BROWSER PAGE LOADER: This document loading check 
    // supports older browsers, including IE4+ and many older 
    // browsers like Firefox (2006), early Chrome (2010), etc.
    // Note: "interactive" is when the document has finished
    // loading and the document has been parsed and DOM is complete,
    // but sub-resources such as scripts, images, style sheets and
    // frames are still loading. "complete" is when all resources
    // are loaded and right before the "Window.load event fires.
    // Note: "document.onreadystatechange" has support in very old
    // browsers amd may have support from IE4+, It fires as each
    // state of the docuent load process changes below. IE 4-9 only
    // supported "readyState" of "complete".

    // If the document is already loaded and those events fired, run the JQuery function above.

    if (document.readyState) {
        if (document.readyState === "complete" // IE 4-9 only knows "complete"
            || document.readyState === "loaded") {
            JQueryStart("Document fully loaded (early)");
        } else {
            // New browsers should run scripts when the HTML is
            // parsed and the DOM built. Older IE browsers will
            // not support the "DOMContentLoaded" event and instead
            // fire when complete below. This allows newer browsers
            // to fire only when the HTML DOM is ready, which happens
            // right after the readyState=interactive fires.

            if (window.addEventListener) {
                // Listen for the "DOMContentLoaded" event, which occurs
                // after "interactive" but when the HTML DOM is complete.
                // This means the DOM is ready but other resources style 
                // sheets, other scripts, images, etc. may not be.

                window.addEventListener('load', function () {
                    JQueryStart("Window fully loaded (2)");
                }, false);
                window.addEventListener('DOMContentLoaded', function () {
                    DOMStart("DOM complete (early)");
                }, false);
            } else {

                // Run the older page "onreadystatechange" for older
                // browsers. Below, runs when page resources are not
                // yet fully loaded, so set up event listeners based
                // on needs of old/new web browsers script support.
                // This fires each time the document readyState changes,
                // except in IE 4-9 that only supports "complete". Below,
                // the DOM is loaded and parsed, but adding "interactive"
                // to the condition below means other resources like CSS, 
                // images, etc may not have completed yet.
                // Note: Add "interactive" below if needing to run early 
                // scripts as soon as the DOM is complete, and do not require 
                // styles sheets, script files, images, other resources, etc.
                // Note: "interactive" fires before "DOMContentLoaded", but in 
                // IE 9 - 11 fires too early before parsing.

                var isDone = false;
                document.onreadystatechange = function () {
                    if (document.readyState === "complete" // IE 4-9 only knows "complete"
                        || document.readyState === "loaded") {
                        if (!isDone) {
                            isDone = true;
                            JQueryStart("Document fully loaded");
                        }
                    }
                    else if (document.readyState === "interactive") {
                        DOMStart("Document interactive (early)");
                    }
                };
            }
        }
    } else {
        // This is a fallback event format that works well in many older browsers.
        window.onload = function () {
            JQueryStart("Window fully loaded (1)");
        };
    };

Solution 10 - Javascript

You can just type window.jQuery in Console . If it return a function(e,n) ... Then it is confirmed that the jquery is loaded and working successfully.

Solution 11 - Javascript

A quick way is to run a jQuery command in the developer console. On any browser hit F12 and try to access any of the element .

 $("#sideTab2").css("background-color", "yellow");

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSoftwareSavantView Question on Stackoverflow
Solution 1 - JavascriptBoltClockView Answer on Stackoverflow
Solution 2 - JavascriptTushar ShuklaView Answer on Stackoverflow
Solution 3 - JavascriptNikoView Answer on Stackoverflow
Solution 4 - JavascriptAlexeinView Answer on Stackoverflow
Solution 5 - JavascriptNika TsilosaniView Answer on Stackoverflow
Solution 6 - JavascriptDexterView Answer on Stackoverflow
Solution 7 - JavascriptDiego FortesView Answer on Stackoverflow
Solution 8 - JavascriptV.VolkovView Answer on Stackoverflow
Solution 9 - JavascriptStokelyView Answer on Stackoverflow
Solution 10 - JavascriptBharadwajView Answer on Stackoverflow
Solution 11 - JavascriptJajikanth pydimarlaView Answer on Stackoverflow