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!