Search code examples
angularjsgruntjsgulpbrowserify

Angular - Place scripts in its own import file


The idea is to have a very thin index.html file, right now its an essay of script tags in development mode like this

<html>
<body>
  <script></script>
  <script></script>
  <script></script>
  <script></script>
  <script></script>
  <script></script>
  <script></script> 
<!-- etc -->
</body>

I thought I could do that by using

<html>
   <body>
   <link rel="import" href="imports.html"
   </body>

With imports.html looking like

<script></script>
<script></script>
<script></script>
<script></script>
<script></script>

But I get all kinds of injector errors. So main question will this approach work with some adjustments?


Solution

  • Yes, use gulp with browserify to let you use require tags just like nodejs, and it will build your dependency chain into one bundled file, which you can then uglify and gzip which will dramatically lower your load time. Gulp has many modules to help with this. I'd recommend browser-sync too.

    I split up my loads into two files, a depends.js which requires all angular dependencies, and a app.js which has my much lighter app code that is changing. I use watchify to monitor my browserify chain and when it triggers it doesn't have to update all the dependencies, it caches non changing files and so my live reload is incredibly fast. This can also be setup to load dependencies asynchronously from the head tag prior to your css which can have a major impact since this contains the majority of your payload. Also when using browserify your source code is way cleaner since it does all the anonymous function wrapping at build time for you.

    I should note that my app.js never physically requires depends.js because that would bundle to 1 package which would slow down live reload builds, and wouldn't allow you to do clever pushes that allow depends.js to stay cached on the client. It just assumes that angular is already defined on the window object, which it is guaranteed to be (described below).

    I use the same setup in prod because it is beneficial to my load times, chrome dev tools network tab shows all of my scripts load asynchronously. You will probably need to wrap your app code in a function and execute it at the end of your depends code if you load async because otherwise your app will try and call angular before it's loaded, since the app code is generally much smaller than its dependencies.

    Here is an example of how clean the code becomes - angularjs browserify