如何在加载jQuery后运行jQuery函数?

Lui*_*uiz 2 html javascript jquery

在我的网站上,我正在异步加载jQuery.

为了做到这一点,我必须在真正加载之后才运行jQuery函数.

我尝试了两种纯JS方式:

<script src="js/jquery-2.2.2.min.js" async></script>
<script>
    window.addEventListener('load', function() {
        //stuff
    }, true);
</script>
Run Code Online (Sandbox Code Playgroud)

window.onload = function() {
    //stuff
}
Run Code Online (Sandbox Code Playgroud)

但即便如此,我仍然得到 Uncaught TypeError: $(...) is not a function at...

在lib完全加载后如何触发jQuery函数?

Pra*_*lan 6

只有在使用脚本标记加载jQuery库之后才需要添加脚本.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  // your code should be here
  alert(typeof jQuery)
</script>
Run Code Online (Sandbox Code Playgroud)


文件准备处理程序是用来执行的DOM元素被加载后,才代码.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  console.log('Outside document ready handler ' + $('.test').length)

  $(document).ready(function() {
    console.log('Inside document ready handler ' + $('.test').length)
  });
</script>
<div class="test"></div>
Run Code Online (Sandbox Code Playgroud)


更新1:你可以使用deferif脚本在文件中,参考以下问题:jquery加载异步和就绪函数不工作


更新2:或者您可以load使用addEventListener方法将事件处理程序绑定到脚本标记.

<script async id="script" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
  document.getElementById('script')
    .addEventListener('load', function() {
      alert(typeof jQuery)
    });
</script>
Run Code Online (Sandbox Code Playgroud)

仅供参考:我不知道你为什么这样做,为了优化内容加载的速度,最好移动脚本标签,最后body有助于首先加载内容.


Tra*_*ton 6

你可以这样做:

function checkVariable(){
   if ( window.jQuery){
      Do your jquery stuff here
   }
   else{
      window.setTimeout("checkVariable();",100);
   }
}
checkVariable();
Run Code Online (Sandbox Code Playgroud)

格式化的道歉......现在卡在我的手机上.

  • 您需要将 `windows.setTimeout` 更改为 `window.setTimeout` (2认同)