简体   繁体   中英

async script attribute vs async property?

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 compatible with older browsers .

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

Example :

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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