Hacker News new | past | comments | ask | show | jobs | submit login

Best practice is to always add [async] or [defer] attributes. Document location will always be a hint to the browser, but you shouldn't toss it in the head if you don't need it till later.



If your scripts are going to be downloaded asynchronously because you've used "async" or "defer", you should place them before any blocking resources, like CSS for example, otherwise you're sat waiting for that blocking resource to download before you even start downloading the scripts.

This is why my script tags end up in the head now, because I want to place them before the CSS tags, and I want to fetch the CSS before the body starts being displayed.

I tend to use defer rather than async because I want the scripts to execute in the order I add them to the page, and only once the body has been fully constructed.

That said, if you have to support old browsers, make sure you research which ones support async/defer, and which ones have buggy implementations. caniuse.com is your friend.

[*] If I'm wrong with any of the above, please correct me. Just checked your profile and you seem well qualified to contradict me.


You don't have to place things in order to addressing blocking behavior better. Browsers have already tackled that optimization for you. https://groups.google.com/a/chromium.org/forum/#!topic/loadi...


> Best practice is to always add [async] or [defer] attributes.

Can you give a reference for that?

HTML5 Boilerplate, Yeoman's generator-webapp and Google's Web Starter Kit do not come with these script attributes OOTB.

EDIT: ha I just noticed your username. Maybe you can tell me why those projects don't come with async script tags?


Because we've been wimps. :) If you don't care about IE8 or IE9 you can use [defer]. [async] is always fine, but less attractive. But srsly [defer] is equivalent to [theresnodocumentwriteinhere].


I was not familiar with the async attr in a script tag before. Thank you for pointing this out. I also use the scaffolding tools the other commenter noted and never saw this attribute before.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: