本文介绍了异步脚本属性vs异步属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async 属性是HTML5的最新功能,

表示下载的文件不会调用 document.write 并且可以在页面处理时下载

The async attribute , is a more recent feature of HTML5,
which indicates that the downloaded file won’t call document.write and can be downloaded as the page is being processed

但我听说另一种方式以异步方式加载脚本,向后兼容
使用旧浏览器

But I've heard that there’s another way to load scripts asynchronously that’s backward compatiblewith older browsers.

事实证明我可以重新创建行为通过动态
async 属性中实现,在JavaScript中创建脚本DOM元素并将其附加到页面。

It turns out that I can re-create the behavior achieved by the async attribute by dynamicallycreating a script DOM element in JavaScript and appending it to the page.

示例:

var script = document.createElement('script');
script.src = 'http://camerastork.com/widget.js?product=1234';
script.async = true
...

所以如果它是旧的浏览器,不支持 async - 怎么可能 - 我仍然可以使用 .async 属性?

So if it's for old browsers , which don't support async-- how can it be - that I can still use .async property ?

推荐答案

async 属性/属性比你想象的要早(至少在一些浏览器世系中)。但其真正的原因是大多数浏览器始终通过 createElement 处理添加到DOM的所有脚本元素。 / appendChild asasynchronous(不需要 script.async = true )。几年前,只有几个浏览器同步处理它们(在脚本被提取和执行之前没有执行下一行代码),并且有问题的浏览器已经更新了它们的行为。

The async attribute/property is older than you think it is (at least in some browser lineages). But the real reason this works is that the majority of browsers have always treated all script elements added to the DOM via createElement / appendChild as "asynchronous" (without requiring script.async = true). There were only a couple of browsers, years ago, that treated them synchronously (didn't execute the next line of code until the script had been fetched and executed), and the browsers in question have since updated their behavior.

这篇关于异步脚本属性vs异步属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 14:20