Article Image
read

Using AngularJS templates / partials is awesome. It gives you the ability to be modular. The problem with that is that it creates an extra http request for each template (assuming you have a different template file for each template, which you should!).

A cool trick is using Grunt/Gulp plugin called html2js (if you're not using Grunt.js/Gulp.js, this could be a great time to start to). This plugin will pre compile all of your html templates to javascript, wrapping it as an Angular.js module and putting it into $templateCache. The output javascript could be concatenated into the main js file, minified and gZipped. Cool...

Installing the plugin:

Grunt

npm install grunt-html2js --save-dev

Gulp

npm install --save-dev gulp-html2js

Configuration file should look something like this (Grunt)

This will create a module named "app.templates", which you will be able to add as a dependency to your main app. You will also have to pre-compile the cached templates:

An example for a simple auto-generated javascript file:

For a complete demo using html2js you can refer to my angularjs-realworld demo in Github.

Blog Logo

Yaniv Efraim


Published

Image

Advanced Front End topics

Back to Overview