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!
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.
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.