当我们在 document.ready
中调用带有属性 async="true"
的 javascript 时会发生什么。例如,
$(document).ready(function() {
var ma = document.createElement('script');
ma.type = 'text/javascript';
ma.async = true;
ma.src = 'test.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ma,s);
});
$(document).ready
中的脚本将在加载 DOM 后立即执行。如果我们将用于调用脚本的 async = true
放入其中会发生什么? test.js
会在 DOM 准备好之前加载吗?
最佳答案
通过 DOM 操作添加的脚本与添加它们的 JavaScript 不同步,独立于 async
属性。
async
attribute在存在于初始 HTML 中的脚本中发挥更大的作用 - 在“就绪”之前 - 或者当添加多个脚本元素并且执行顺序必须与 DOM 插入顺序匹配时:
Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously ..
.. script-inserted scripts execute asynchronously in IE and WebKit, but synchronously [wrt the insertion order of the script elements] in Opera and pre-4.0 Firefox. .. To request script-inserted external scripts be executed in the insertion order in browsers [..] set
async=false
on the scripts you want to maintain order ..
浏览器将“在元素添加到 DOM 后的某个时刻”开始加载新脚本元素引用的脚本,并且引用的脚本只会执行一次加载。但是,insertBefore
返回立即 并且引用的脚本不 保证加载 - 什么async
无关紧要设置为。
在这种情况下,test.js 代码保证仅在“将脚本元素添加到 DOM 之后之后”运行到 DOM - 这自然必须是之后 ready 函数被调用,这是添加元素的地方。
由于浏览器有一个单一的执行上下文,并且添加 DOM 元素是一个异步操作(wrt 正在执行的外部脚本),这也意味着 test.js 中的代码将仅运行“在某个之后,就绪函数结束”。并且,就绪函数在响应“DOM 就绪”而被调用之前不会开始(或结束)。
设置 async
标志(为任何值)不会改变上述内容。
关于javascript - 在 document.ready 中使用 async=true 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20536047/