Checking if jquery is loaded using Javascript

2019-01-01 12:38发布

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>

7条回答
闭嘴吧你
2楼-- · 2019-01-01 13:07

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.

查看更多
临风纵饮
3楼-- · 2019-01-01 13:08

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')


and

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


Hope this covers all good ways to get this thing done!!

查看更多
怪性笑人.
4楼-- · 2019-01-01 13:12

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

查看更多
孤独总比滥情好
5楼-- · 2019-01-01 13:14

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

查看更多
长期被迫恋爱
6楼-- · 2019-01-01 13:24

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");
    }
}
查看更多
临风纵饮
7楼-- · 2019-01-01 13:30
if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}
查看更多
登录 后发表回答