Years ago I've learned that <script>
in <head>
will block page rendering, reducing website's perceived load time, instead they should be included in the end of the <body>
.
I guess this doesn't apply for a webapp, which doesn't work without JavaScript anyway. In fact, it should be even desirable to load them first because of templates compilation. However, in all tutorials on Ember and Angular I see the scripts included at the end. Is it still reasonable?
There are merits for loading scripts in <head>
. $.ajax
, for example, can begin making requests much before the DOM is ready. So, if your webapp relies on external data (e.g. configuration JSON), having the $.getJSON()
part of your app in head
will decrease perceived load time.
Of course, like you said, head
scripts are blocking. It is largely case-by-case where your scripts ought to be.
With regards to angular, most of the time it makes very little difference where you put them. In most web app angular situations, you will have an incredibly small starting page. Most of your actual functionality will be inject later via view or ui-view (if you're using angular ui).
Angular also includes a directive called ng-cloak that will hide your app until the templates have compiled and rendered. This is a nice way to hide the template syntax from the end user until it's ready.
On the topic of placing scripts, the official documentation on Angular says:
Place the script tag at the bottom of the page. Placing script tags at the end of the page improves app load time because the HTML loading is not blocked by loading of the angular.js script. http://docs.angularjs.org/guide/bootstrap
In practice, unless you have a lot of other scripts (jQuery widgets, plugins, etc) that execute immediately, you won't see a performance difference in small apps. If you get to an application with a large enough set of controllers, it won't hurt to place them at the bottom. At that point though, you should really consider a much more proven technique: reduce http requests.
That's a whole other can of worms, but an automated task runner like Grunt could handle minifying and combining your different controller scripts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With