简体   繁体   English

脚本的异步属性&& document.ready?

[英]Script's async property && document.ready?

I create a script element ( document.createElement('script') ....) I set its async property by: x.async=true 我创建了一个脚本元素( document.createElement('script') ....)我通过以下x.async=true设置其异步属性: x.async=true

Which means that the scripts are not blocking and the execution order between each other - is not preserved ( as opposed to defer (which also waits for dom to load.)) 这意味着脚本没有阻塞,彼此之间的执行顺序 - 不会被保留(而不是defer (也等待dom加载)。)

Question : 题 :

But if I set the async attribute - does it mean that I must use document.ready ? 但是,如果我设置async属性 - 这是否意味着我必须使用document.ready? because I could run a method which is declared in the script file which is future to be downloaded - hence error . 因为我可以运行一个在脚本文件中声明的方法,该方法将来会被下载 - 因此会出错

From personal experience, it is better to use document ready or window load in the async script file just to be safe. 根据个人经验,最好在异步脚本文件中使用文档就绪或窗口加载,以确保安全。

This is because after the first load, the JavaScript file would be cached by the browser, and depending on the browser/circumstances, can load from cache and try to execute before the DOM is ready. 这是因为在第一次加载之后,JavaScript文件将被浏览器缓存,并且根据浏览器/环境,可以从缓存加载并尝试在DOM准备好之前执行。

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

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