Last active
March 9, 2017 09:05
-
-
Save pradeepn/c76a8be24e6a51185b76963c5fead009 to your computer and use it in GitHub Desktop.
Inject CSS in ngroute resolve method to lazy load css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| .factory("injectCSS", ['$q', '$http', 'MeasurementsService', function($q, $http, MeasurementsService){ | |
| var injectCSS = {}; | |
| var createLink = function(id, url) { | |
| var link = document.createElement('link'); | |
| link.id = id; | |
| link.rel = "stylesheet"; | |
| link.type = "text/css"; | |
| link.href = url; | |
| return link; | |
| } | |
| var checkLoaded = function (url, deferred, tries) { | |
| for (var i in document.styleSheets) { | |
| var href = document.styleSheets[i].href || ""; | |
| if (href.split("/").slice(-1).join() === url) { | |
| deferred.resolve(); | |
| return; | |
| } | |
| } | |
| tries++; | |
| setTimeout(function(){checkLoaded(url, deferred, tries);}, 50); | |
| }; | |
| injectCSS.set = function(id, url){ | |
| var tries = 0, | |
| deferred = $q.defer(), | |
| link; | |
| if(!angular.element('link#' + id).length) { | |
| link = createLink(id, url); | |
| link.onload = deferred.resolve; | |
| angular.element('head').append(link); | |
| } | |
| checkLoaded(url, deferred, tries); | |
| return deferred.promise; | |
| }; | |
| return injectCSS; | |
| }]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Routing setup | |
| .config(function ($routeProvider) { | |
| $routeProvider | |
| .when('/home', { | |
| controller: 'homeCtrl', | |
| templateUrl: 'home.tpl.html' | |
| }).when('/users', { | |
| controller: 'usersCtrl', | |
| controllerAs: 'vm', | |
| templateUrl: 'users.tpl.html', | |
| resolve: { | |
| load: ['injectCSS', function (injectCSS) { | |
| return injectCSS.set("users", "users.css"); | |
| }] | |
| } | |
| }).otherwise({ | |
| // default page | |
| redirectTo: '/home' | |
| }); | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment