开发者

Checking if jquery is loaded using Javascript

开发者 https://www.devze.com 2023-04-03 15:12 出处:网络
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:

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  
               ale开发者_如何学JAVArt("Yeah!");
             } else {
               // jQuery is not loaded
               alert("Doesn't Work");
             }
          });
        </script>


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");
    }
}


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) {
    console.log("jquery is loaded");
} else {
    console.log("Not loaded");
}

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


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


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.


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().


NOTE: Do not use jQuery to test your jQuery (Isn't that obvious)

Using jQuery ✘

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

Using javaScript ✔

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


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();


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.


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)");
        };
    };


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.


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");

Checking if jquery is loaded using Javascript

0

精彩评论

暂无评论...
验证码 换一张
取 消