4

Have been studying the use of async and defer in script tags. Given the following...

async - Allows the rest of the html to parse, while the JS script is being loaded. Once the script is completely loaded then the html parser is paused to execute the script. However, note that the order of loading can't be controlled.

defer - Also allows the rest of the html to parse, however the loaded js is only executed once the html parsing is complete.

So, if you can afford to show your html without loading your js script first... use async. If more than one script is involved and the order they are loaded matters then use defer. On the other hand, if your scripts MUST be loaded first (and can't be rewritten to allow the html to parse first) then just load the script without using async or defer in the header.

How would this fit with modern frameworks like AngularJS... since, delaying their loading results in an error. Any pointers would be appreciated.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Grateful
  • 9,685
  • 10
  • 45
  • 77
  • 2
    Possible duplicate of [Script Tag - async & defer](http://stackoverflow.com/questions/10808109/script-tag-async-defer) – Bhojendra Rauniyar Jan 21 '16 at 04:52
  • Have changed the question above. Please provide feedback. – Grateful Jan 21 '16 at 05:15
  • Angular just has to be loaded before your custom scripts otherwise you get errors since angular isn't defined yet so asynchronous would not be a good idea. Defer would work though. Another option that might be simpler then using defer is simply put your script tags at the bottom of your html body element so they are loaded after the html. – Binvention Jan 21 '16 at 05:21
  • Uhh... how would defer work!? I thought Angular is required beforehand, so wouldn't using defer (or end of body inclusion) defeat the purpose? – Grateful Jan 21 '16 at 05:27
  • @Grateful defer will load scripts in order. Manual bootstraping angular will solve this, but not if lazy loadind controllers/providers, which I do a lot.. – Bernardo Dal Corno Dec 02 '17 at 14:06

1 Answers1

0

Considering that an Angular app depends entirely on the Angular JS files and dependencies, it doesn't make much sense to defer or async them unless you have a fallback (like a loading state, perhaps?). With that said, however, adding defer to all of the scripts would likely work fine, but not do much in terms of performance. Adding async could break things since certain dependencies are required to load before others.

karns
  • 5,391
  • 8
  • 35
  • 57