---
title: Preload Resource Data into AngularJS
teaser:
tags: web,javascript,angularjs
author: Greg Lazarev
published_on: 2014-07-15
---

Preloading, or bootstrapping, data resources from the server via <abbr
title="HyperText Markup Language">HTML</abbr> 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 <abbr title="HyperText Markup
Language">HTML</abbr> page. Yet, the following implementation can be utilized
for such a purpose.

First, a directive needs to exist:

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

Now, this directive can be used in the <abbr title="HyperText Markup
Language">HTML</abbr> that is sent by the initial request, and populated with
<abbr title="JavaScript Object Notation">JSON</abbr> data:

```erb
<div ng-cloak preload-resource="<%= UserSerializer.new(@user).to_json %>"></div>
```

The `preloadResource` directive reads the <abbr title="JavaScript Object
Notation">JSON</abbr> 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:

```javascript
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.
