Regarding AngularJS data preloading
🕓 Jun 27th 2014
A few weeks ago Gabriel Scholz wrote a blog about frictionless data preloading in AngularJS which I quite enjoyed. He also updated the blog later conceding that there was an even better method. From my experience, neither options were ideal and I wanted to write a short entry on how I propose we preload data in AngularJS.
A few objectives
I think that there are a few key attributes that a good solution has to have:
- It shouldn't pollute the global name space
- It shouldn't require declaration within the scope of
ng-appin the DOM
- You should be able declare multiple pieces of data separately and concatenate them
- Preloaded data should be optional, not a dependency
The two previously suggested solutions
Gabriel suggested that we put JSON objects inside of
scripttags, identify them by a type such as "text/preloaded" and then parse and add them to a
preloadedconfig object via a directive that looks for
scripttags. I actually really like this idea but it didn't satisfy rule #2. Your script tag needed to be inside of
The blog entry was updated with a solution of simply declaring another module within
scripttags. However, this solution doesn't satisfy rules #3 and #4 very well. I would hate to be declaring and depending on multiple modules of preloaded data.
My proposed solution
I actually really like Gabriel's method, except for running the search for preloaded data inside of a directive. Instead I say it should be done inside of a
.run(), which occurs after
.config() and before
.controller(). Like so:
This method satisfies all 4 rules I stated above. I would love to hear feedback if anyone has a better method.