Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should scripts be included in head in case of a webapp?

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?

like image 503
Pavlo Avatar asked Nov 28 '22 08:11

Pavlo


2 Answers

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.

like image 44
Brian Avatar answered Dec 10 '22 04:12

Brian


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.

like image 60
Mike Robinson Avatar answered Dec 10 '22 04:12

Mike Robinson