LinMinquan's Blog

Experience technology to change life

html中script的属性async defer

在用到google map时,其最简单的demo里用到了async和defer。script是html的element,async和defer是script的attributes。

google map demo

https://developers.google.com/maps/documentation/javascript/examples/map-simple

网上有蛮多async和defer分别的作用及对比,两者在fetch其js file时都是异步,这时不影响html加载。async是一fetch到js file就执行,defer是fetch到后等待html加载完了再执行。但如果这两个都放在 前面的地方,那就区别不大了。

另外,async适合这个js file没有依赖其它的file,它自己执行完了不妨碍其它js执行。

async vs defer attributes (这个链接图示了两者的区别,要看)

http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

Asynchronous vs Deferred JavaScript (这个链接的结果很重要,要看)

https://bitsofco.de/async-vs-defer/

但上面的文章没有提到这两个属性同时使用的情况,google map demo就是同时用的。

w3中关于这两个属性同时使用有说明。

https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#attr-script-async

The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.

也就是说同时用是为了兼容旧浏览器,旧浏览器可以识别defer(async将被忽略),那么可以推断,在modern web browsers里,写了两个属性时,应该识别的是async。

https://stackoverflow.com/questions/13821151/can-you-use-both-the-async-and-defer-attributes-on-a-html-script-tag

上面的链接里有个comment,

1.both async defer exist, modern browsers run as async; 2.both async defer exist, old browsers run as defer instead of default behavior

我觉得这个comment是对的。

https://developers.google.com/maps/documentation/javascript/tutorial

The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads.

上面链接中说明了为啥google map中要用async。但感觉讲得有问题,这个js在execution时还是会影响website render,除非是把 script element放在 靠近的前面。

 


Share