即时加载jQuery [英] Loading jQuery on-the-fly

查看:46
本文介绍了即时加载jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚我的代码在这里出了什么问题。我试图动态加载jQuery,如果它不存在于页面上。

I can't figure out what is wrong with my code here. I am trying to load jQuery dynamically if it is not present on the page.

<head>
  <script>
     (function() {
         if (typeof jQuery != 'undefined') {
         /* jQuery is already loaded... verify minimum version number of 1.4.2 and reload newer if needed */
         if (/1\.(0|1|2|3|4)\.(0|1)/.test(jQuery.fn.jquery) || /^1.1/.test(jQuery.fn.jquery) || /^1.2/.test(jQuery.fn.jquery)|| /^1.3/.test(jQuery.fn.jquery)) {
         loadJQ();
         }
      } else {
           loadJQ();
        }

    function loadJQ() {
    /* adds a link to jQuery to the head, instead of inline, so it validates */ 
    var headElement = document.getElementsByTagName("head")[0];
    linkElement=document.createElement("script");
    linkElement.src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
    linkElement.type="text/javascript";
    headElement.appendChild(linkElement);
   //alert(headElement);
   }

   })();

  </script>
</head>

这是我的身体。

 <body>
   <button>Click me</button>
   <script type="text/javascript">
     $(document).ready(function(){
   alert("hello");
     $("button").click(function(){
     $(this).hide();
    });
   });
   </script>
 </body>

当我把它放在一个html页面中时,我收到一个错误,说$ is not defined。任何人都知道为什么?

When I put this in a html page I get an error saying that "$ is not defined". Anyone has any idea why?

推荐答案

在我的一位朋友的帮助下,发现上述代码有什么问题。

With help of one my friend, found what is the problem with above code.

当document.ready运行时,jquery不在页面上(运行有两个onReady元素)...并且由于addToHead版本是非阻塞的,因此其余的javascript执行并行并失败。

When the document.ready runs, jquery is not on the page (there are two onReady elements running)… and since the addToHead version is non-blocking, the rest of the javascript executes in parallel and fails.

我在body标签启动后添加了它并且工作正常:

I added this just after the body tag starts and it works fine:

<script type="text/javascript">
   if (typeof jQuery == 'undefined') {
     document.write('<scr'+'ipt type="text/javascript" src="http://ajax.googleapis.com /ajax/libs/jquery/1.7.1/jquery.min.js">'+'</scr'+'ipt>');
  }
</script>

这篇关于即时加载jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆