在页面底部编写脚本和在其中编写脚本有什么不同/优点/缺点
$(document).ready(function(){});
在页面底部编写脚本和在其中编写脚本有什么不同/优点/缺点
$(document).ready(function(){});
Very little in and of itself, either way the DOM will be ready for you to operate on (I was nervous about that until I read this from Google). If you use the end of page trick, your code may get called the slightest, slightest bit sooner, but nothing that will matter. But more importantly, this choice relates to where you link your JavaScript into the page.
如果您在head
中包含script
标签,并且依赖ready
,那么浏览器在向用户显示任何内容之前会遇到script
标签.在正常的事件过程中,浏览器突然停止并下载脚本,启动JavaScript解释器并将脚本交给它,然后等待解释器处理脚本(然后jQuery以各种方式监视DOM是否准备就绪).(我说"在正常情况下",因为有些浏览器支持script
个标签上的async
or defer
个属性.)
如果在body
元素的末尾包含script
标记,浏览器不会完成所有这些操作,直到页面基本上已经显示给用户.这会提高页面的感知加载时间.
因此,要获得最佳的加载时间,请将脚本放在页面底部.(这也是the guideline from the Yahoo folks.)如果您要这样做,那么就不需要使用ready
,当然,如果您愿意的话,也可以使用ready
.
There's a price for that, though: You need to be sure that the things the user can see are ready to be interacted with. By moving the download time to after the page is largely displayed, you increase the possibility of the user starting to interact with the page before your script is loaded. That's one of the counter-arguments to putting the script
tag at the end. Frequently it's not an issue, but you have to look at your page to see whether it is and, if so, how you want to deal with it. (You can put a small inline script
element in the head
that sets up a document-wide event handler to cope with this. That way, you get the improved load time but if they try to do something too early, you can either tell them that or, better, queue the thing they wanted to do and do it when your full script is ready.)