简体   繁体   English

异步/延迟 JavaScript 问题

[英]Asynchronous / Deferred JavaScript issue

I am using this code at footer for Eliminate render-blocking resources我在页脚使用此代码来消除渲染阻塞资源

<script async or defer src="/jquery.js">
 /* custom code  */
<script>    
$(document).ready(function(){
$('.menu-bar').click(function(){
   $('.nav-bar').slideToggle();
  }); 
  $('.dropdown').click(function(){
      $(this).toggleClass('inDrop');
      $('.dropdown-menu').slideToggle('slow');
  });

});
</script>

Now I am getting Uncaught ReferenceError: $ is not defined error.现在我收到Uncaught ReferenceError: $ is not defined错误。

what is best way to use Asynchronous / Deferred JavaScript什么是使用异步/延迟的最佳方法 JavaScript

Async is tough, because it'll execute the minute it finishes, so you can't tell the order in which scripts will finish being retrieved.异步很难,因为它会在它完成的那一刻执行,所以你不能告诉脚本完成检索的顺序。 It's also negligible compared to defer, which will wait until the HTML parses before it starts, and then it starts in order.与 defer 相比也可以忽略不计,它会等到 HTML 解析后才开始,然后按顺序开始。

Here are two cases:这里有两种情况:

<HTML start>
<async js 1>
<async js 2 (dep on 1)>
<HTML parses>
<js 2 finishes and executes>
<js 1 finishes and executes>
<HTML finishes parsing>

Defer:推迟:

<HTML start>
<defer js 1>
<defer js 2 (dep on 1)>
<js 2 loads, and waits>
<js 1 loads, and waits>
<HTML finishes parsing>
<js 1 is fired>
<js 2 is fired>

You can keep your dependencies with defer .您可以使用defer保留您的依赖关系。 I use defer 99.9% of the time, and only if the order of your scripts is not important.我使用 defer 99.9% 的时间,并且仅在脚本的顺序不重要的情况下使用。

If you need the inline js to wait until the dependencies are loaded, you would wait for the document ready state.如果您需要内联 js等到加载依赖项,您将等待文档准备好 state。

jQuery: jQuery:

`$(document).ready(function() {
  ...code here...
};`

vanilla JS:香草JS:

`document.addEventListener("DOMContentLoaded", function() {
  ...code here...
};`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM