Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the <script async> tag with Angular.js

Ilya Grigorik recommends the use of the <script async> tag where possible.

Is there a clean, preferred way to load an Angular.js app using the tag, without using tools like require.js or the $script.js tool recommended by the angular-seed?

The obvious issue is execution order. e.g. preventing:

Uncaught ReferenceError: angular is not defined

https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/

like image 507
R.V.d.M Avatar asked May 22 '14 17:05

R.V.d.M


People also ask

What is the use of async in script tag?

Definition and Usage If the async attribute is set, the script is downloaded in parallel to parsing the page, and executed as soon as it is available. The parsing of the page is interrupted once the script is downloaded completely, and then the script is executed, before the parsing of the rest of the page continues.

What is the benefit of adding async to script as attributes?

And according to Steve Souders site, "the main benefit of this [async attribute] is it tells the browser that subsequent scripts can be executed immediately – they don't have to wait for ga. js".

Is AngularJS asynchronous?

In AngularJS, we have the $q object which is a service that helps to execute a function asynchronously and use values returned from these calls for further processing. This is an implementation of promise or deferred object.

What's the difference between async and defer in script tag?

In practice, defer is used for scripts that need the whole DOM and/or their relative execution order is important. And async is used for independent scripts, like counters or ads. And their relative execution order does not matter.


1 Answers

If there's something useful you can show without angular (e.g., a pre-generated content using a headless browser) AND nothing but your script depends on it1, then there can be a solution:

  • load angular.js using async
  • encapsulate you code in a function body
  • add a loop checking if angular is defined
    • and sleeping for a few milliseconds if not
    • otherwise, executing your code and breaking out of the loop

This sort of busy waiting is ugly, but I can't see how to get called back when the loading finishes. It may work or not, I haven't tried it yet.

It's quite possible that I'm doing nothing but a primitive version of what the frameworks do.

If you don't need it to work in all browsers, then there's the defer tag. To me, defer looks like async done right.


1 So I guess, users of angular-route.js or alike are out of luck. This is just a guess as I've never tried to load the two out of order.

like image 170
maaartinus Avatar answered Sep 30 '22 18:09

maaartinus