简体   繁体   中英

Prefetching $templateCache

My angularjs application basically loads in 4 steps:

  • main HTML
  • all scripts and CSS files
  • $templateCache , let's call it template.html
  • images

I guess, I should bypass the $templateCache when loading the starting page. But for now, I'd like to start fetching template.html ASAP, ie, at the same time as the scripts get loaded.

The possibly relevant piece of my code looks like

<script src='//ajax.googleapis.com/.../angular.min.js'></script>
<script src='/my.js'></script>
<link href='/my.css' media='all' rel='stylesheet'/>

Here, my.js contains all my scripts and gets loaded at the same time as angular. Is there something allowing me to fetch template.html in the same way, so it gets put into the browser's cache?

Update

I've tried two prefetching possibilities, both failed:

<link href="template.html" rel="prefetch"/>

and

<iframe class=invisible src="template.html"></iframe>

The first gets cancelled and the second comes too late to be effective.

As the HTML can't be fetch soon enough, the whole script directive is completely pointless.

According to runTarm's suggestion, I ended up generating the Javascript instead. All it takes is

.factory('$templateCache', function($cacheFactory, $http, $injector) {
    var cache = $cacheFactory('templates');
    cache.put("MY_PAGE_1", "ESCAPED_TEXT_1");
    cache.put("MY_PAGE_2", "ESCAPED_TEXT_2");
    ...
    return {
        get: function(url) {
            var fromCache = cache.get(url);
            return fromCache ? fromCache : $http.get(url);
        }
    };
}

In the escaped text you must honor the 1024 string-literal length limit and escape newlines and double quotes. That's all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM