简体   繁体   中英

Angular Script Loading inside partial view - caching issues

I am having issues with loading JavaScripts inside a partial view in my Angular application.

This is my setup: ui-router sets the ui-view for requests to /profile as <app-home-profile></app-home-profile> .

The appHomeProfile directive is set up as follows:

app.directive('appHomeProfile', function() {
    return {
        restrict: 'E',
        templateUrl: 'templates/user/profile.html',
        controller: ...,
        controllerAs: 'profileCtrl'
    }
});

Now, inside the profile.html file I include the standard HTML and at the bottom of it some JavaScript dependencies:

<script type="text/javascript" src="/javascripts/myScript1.js"></script>
<script type="text/javascript" src="/javascripts/myScript2.js"></script>

The problem is that the server logs show that Angular is adding the timestamp to the requests, therefore not allowing to cache any of the scripts! This doesn't happen with scripts loaded the "usual" way in the head of the document.

GET /javascripts/myScript1.js?_=1437207405398 200 2.356 ms - 22524
GET /javascripts/myScript2.js?_=1437207405399 200 1.873 ms - 29695

Any help on how to solve this is appreciated!

Thanks, Nick

As opposed to jQuery, Angular doesn't support <script> in requested templates because of jqLite simplified implementation. It can be fixed like that .

The reason why it works in your example is because you're using jQuery in your app, so it manages DOM instead of jqLite. Timestamps in AJAX requests are added to disable browser caching, it is default behaviour for jQuery. It can be disabled with

app.config(function () {
  angular.element.ajaxSetup && angular.element.ajaxSetup({ cache: true });
});

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