Loading Client Side Templates in Angular JS

One of the features of Angular JS is client routing. This enables us to create single page applications (SPA) by which our site loads an initial html page and every subsequent page is brought in dynamically without triggering a full page refresh.

I was giving a presentation on Angular recently and someone in the audience asked if the templates where downloaded when the web app started, or dynamically as the user navigates to a specific page. This is a great question because on a complex multi-page site, you don’t want to load the templates upfront.

So I decided to investigate. Fortunately, this was an easy thing to do using the Chrome Dev Tools. As part of my talk I built a small sample app called Tweet Save. This web app allows you to search twitter and then bookmark tweets you like. You can see it’s source on github.

The saved tweets page relies on a template called “SavedTweets.html.” Inspecting the network tab on initial load doesn’t show any reference to SavedTweets.html. After clicking the link to the saved tweets page I see the following in my dev tools:

Dev tools

The template is only loaded when the user requests that route from my route provider. If navigate back to the initial search page, then again to saved tweets the two files above will not be downloaded again. That’s because at this point, angular already has the template it needs for that route.

so there we have it. Angular only loads html templates on demand when a user requests that specific route.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s