In this article, I will show you how to load your scripts and styles, using AngularJS and UI Router Resolve, when it's required.
Let's face the problem
You have a page "A" that uses jqGrid plugin and two other pages, "B" and "C," that do not use the plugin. You normally reference jqGrid plugin in your master page, so the pages "A", "B" and "C" will load the script plugin but only page "A" will need it. This is a network performance issue and it becomes complex with many scripts.
The Solution
Use a combination of lazy loading AngularJS plugin and AngularJS UI Router Resolve to do all the necessary steps before the page loads.
Let's see the code given below.
- var definitions = function () {
- var baseFolder = '';
- return {
- grid: {
- devDependencies: [
- baseFolder + 'Css/plugins/jQueryUI/jquery-ui-1.10.4.custom.min.css',
- baseFolder + 'Css/plugins/jqGrid/ui.jqgrid.css',
- baseFolder + 'Css/style.jqGrid.css',
- baseFolder + 'Scripts/plugins/jqGrid/i18n/grid.locale-pt.js',
- baseFolder + 'Scripts/plugins/jqGrid/jquery.jqGrid.min.js',
- baseFolder + 'Scripts/plugins/jquery-ui/jquery-ui.min.js'
- ]
- }
- };
- } ();
The "definitions" hold a configuration for any plugin and scripts/css dependencies.
- (function () {
-
- class AppRoutes {
-
- constructor(
- private utilProvider: App.Util,
- private $stateProvider: ng.ui.IStateProvider,
- private $urlRouterProvider: ng.ui.IUrlRouterProvider
- ) {
- let genericRoute = new App.Core.State.GenericState(this.utilProvider);
-
- this.$urlRouterProvider.otherwise("/login");
- this.$stateProvider.state('homemenu', genericRoute.getState({
- url: '/',
- views: {
- root: {
- template: 'The page does not use GRID scripts. Go to <a ui-sref="homeperson">Person Page</a>'
- }
- }
- }));
- this.$stateProvider.state('homeperson', genericRoute.getState({
- url: '/person',
- dependencies: ['grid'],
- views: {
- root: {
- template: 'That page uses GRID scripts. Back to <a ui-sref="homemenu">Home Page</a>'
- }
- }
- }));
- }
- }
-
- AppRoutes.$inject = [
- 'utilProvider',
- '$stateProvider',
- '$urlRouterProvider'
- ];
-
- angular
- .module('app')
- .config(AppRoutes);
-
- })();
The code given above helps to configure the routes for this article. Just the "/person" route uses "grid" plugin as a dependency. The "getState" method helps you to configure the lazy loading for the dependency and verify in the "definition" object to know which scripts and styles will load.
Try it yourself
Access the home page.
Check in Fiddler, no scripts and styles for GRID have been loaded.
Click Person Page link and it will navigate to person page.
Check in Fiddler. For this route, our GRID scripts styles have been loaded successfully.