Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use <script defer> safely now?

From what I'm reading, the defer attribute on <script> is now widely supported but I never see it used or mentioned.

If you don't need to defer inline scripts and don't add scripts dynamically (which cause problems in IE9- and Safari 4-), it seems that you could use it reliably and have scripts run right before DOMContentLoaded in the specified order (which doesn't happen with async)

This is basically what most websites need: run a couple or more external scripts in sequence, on DOMready. For example:

<script defer src='jquery.js'></script>
<script defer src='jquery.some-plugin.js'></script>
<script defer src='my-scripts.js'></script>

Why isn't it widely used? Can I actually use it now?

like image 681
fregante Avatar asked Dec 27 '13 12:12

fregante


People also ask

Should I use script defer?

You should use defer for all other scripts. defer is great because it: Gets loaded as soon as possible — so it reduces load times. Doesn't execute until everything you need is ready — so all the DOM you need is there.

What happens when you defer JavaScript?

The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script loads “in the background”, and then runs when the DOM is fully built.

What is the purpose of script defer?

Scripts with the defer attribute will execute in the order in which they appear in the document. This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse.

Where do defer scripts go?

The position matters A very common solution to this issue is to put the script tag at the bottom of the page, just before the closing </body> tag. In doing so, the script is loaded and executed after all the page is already parsed and loaded, which is a huge improvement over the head alternative.


1 Answers

I did a bit more research and I found that problems with defer don't stop at inline scripts and scripts added dynamically in IE9. There's a long list of problems and inconsistencies with various browsers on the HTML5 Boilerplate GitHub https://github.com/h5bp/lazyweb-requests/issues/42

It's such a shame, I feel that they should have tried improving on defer rather than working on the dubious async (dubious because it's only useful if the scripts don't depend on each other, which is rare for me)

like image 166
fregante Avatar answered Sep 17 '22 16:09

fregante