Page speed - any problems with simply using defer attribute?

这一生的挚爱 提交于 2019-12-06 12:54:31

问题


Google recommends scripts should be "deferred", but they do not mention the defer attribute of the <script> tag. I wonder why they don't even mention it, considering it has been around a while.

Instead they suggest injecting scripts into the DOM. Is there any particular benefit of this over using the much simpler and cleaner defer attribute?

https://developers.google.com/speed/docs/best-practices/payload?csw=1#DeferLoadingJS

I gather there are some minor issues with old browsers but I am not supporting anything before IE10 and mostly interested in optimising for mobile browsers.

UPDATE: As an interesting note it turns out you can't use any script loading technique if you are using google maps API. The maps API uses document.write to load other scripts, so it cannot be used in a deferred or async script and it cannot be injected into the DOM either, because the document.write will not fire. It would be nice if Google followed their own recommendations!


回答1:


You can prevent a script from blocking during load by using the async attribute on modern browsers:

<script async
  src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=apiloaded">
</script>

The defer attribute indicates not to load at all until the page DOM has completely loaded. Defer implies async.

For older browser support, the page speed code you linked is correct.

With the Google Maps API, you must use a callback parameter when loading the API asynchronously. This causes the api to use dynamic script insertion rather than document.write calls internally. You can specify an empty callback parameter as well.

A note on Page Speed

Page speed is an excellent tool to help optimize a web site. I listed the async attribute because it allows the maps api to be downloaded in parallel (non-blocking). Page speed recommendations may show the most common way to decrease load times, but they are definitely not the only way.

Optimizing map load times



来源:https://stackoverflow.com/questions/20016788/page-speed-any-problems-with-simply-using-defer-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!