Preload Resource Data into AngularJS

Preloading, or bootstrapping, data resources from the server via HTML is a common technique used in JavaScript web development. This technique allows the application to avoid making an extra HTTP request to get that initial data for rendering on the page.

Unfortunately, there isn’t a mechanism built into AngularJS that allows for preloading resources into the initial HTML page. Yet, the following implementation can be utilized for such a purpose.

First, a directive needs to exist:

angular.module("myApp", []).
  directive("preloadResource", function() {
    return {
      link: function(scope, element, attrs) {
        scope.preloadResource = JSON.parse(attrs.preloadResource);

Now, this directive can be used in the HTML that is sent by the initial request, and populated with JSON data:

<div ng-cloak preload-resource="<%= %>"></div>

The preloadResource directive reads the JSON structure into the preloadResource variable on the scope, and removes the element from the DOM to clean-up the final HTML.

The resource data is now available on the scope, and can be used as desired. For example, it can be passed to a corresponding AngularJS factory, like so:

angular.module("myApp", []).
  controller("MainCtrl", [$scope, "User", function($scope, User) {
    $scope.user = new User($scope.preloadResource);

This method requires very little code and reduces the number of HTTP requests made by an Angular application.