jQuery在底部,等待<头部>直到它被加载

jQuery on the bottom, wait execution script on <head> until it is loaded

本文关键字:加载 gt 头部 等待 lt jQuery 底部      更新时间:2023-09-26

我在SO中看到了类似的问题,有人想做同样的事情。不同的情况是,我有一个轻量级的脚本,它监听我有意放在页面顶部的文档根顶部的事件冒泡,我不想把它包装在$(document).ready()中。它看起来像这样:

<html>
<head>
    <script>
        document.documentElement.onclick = function (e) {
        //$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
        }
    </script>
</head>

然后在页面底部附近,我包括这样的jQuery:

<body>
    <script src="./jQuery.js"></script>
</body>
</html>

正如你在<head>上看到的,当我使用$.ajax对某个地方进行ajax调用时,jQuery可能还没有加载,所以当有人点击DOM上的某个东西时,它可能会抛出$ is undefined error,而jQuery还没有加载。我的解决方法可能是使用settimeout,希望稍后加载jquery,代码的工作方式如下:

if (typeof $ === 'undefined'){
  setTimeout(doAJAXJquery, 50);
}else{
  $.ajax(//blablabla) //jQuery loaded and ready to use!!
}

但这是一个非常肮脏的黑客。我应该如何知道jQuery何时完成加载?我放的CCD_ 4只有一个我自己编的任意值。当然,如果jquery没有,它仍然不会起作用;还没有加载,并且已经过了50ms。

有没有更好的解决方法,当jQuery未定义时,它会稍后重试,或者将执行ajax的函数放在一些回调中,当jQuery准备好时执行?谢谢

怎么样

<head>
<script type="text/javascript">
var init = function(){
    document.documentElement.onclick = function (e) {
    //$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
    }
}
</script>
</head>
<body>
<script src="./jQuery.js"></script>
<script type="text/javascript">
init();
</script>
</body>

如果您想执行等待jQuery加载的函数列表(或事件"已激发"),您可以创建自己的"就绪"函数:)

var runList = new Array(), timer = setInterval(function(){
  if (typeof(jQuery) != 'undefined')
  {
     clearInterval(timer);
     if (runList.length>0)  for(var i in runList) runList[i]();  
  }
}, 50);
runList.push(function(){alert(1);});
runList.push(function(){alert(2);});
var jQuery = 1;