[AngularJS] Lazy loading Angular modules with ocLazyLoad

With the ocLazyLoad you can load AngularJS modules on demand. This is very handy for runtime loading of Angular modules in large applications.

 Simple example:

复制代码
angular.module("demo", ["oc.lazyLoad"])
    .controller("AppCtrl", function ($injector, $ocLazyLoad) {

        var app = this;
        app.click = function () {
            $ocLazyLoad.load({
                name: "store",
                files: [
                    "store.js"
                ]
            }).then(function () {
                console.log($injector.get("cart"));
            })

        }
    })
复制代码

 

 

复制代码
'use strict';

// Declare app level module which depends on filters, and services
var App = angular.module('app', ['ui.router', 'oc.lazyLoad'])
  .config(function($stateProvider, $locationProvider, $urlRouterProvider, $ocLazyLoadProvider) {
    $urlRouterProvider.otherwise("/");
    $locationProvider.hashPrefix('!');

    // You can also load via resolve
    $stateProvider
      .state('index', {
        url: "/", // root route
        views: {
          "lazyLoadView": {
            controller: 'AppCtrl', // This view will use AppCtrl loaded below in the resolve
            templateUrl: 'partials/main.html'
          }
        },
        resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
          loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
            // you can lazy load files for an existing module
            return $ocLazyLoad.load({
              name: 'app',
              files: ['js/AppCtrl.js']
            });
          }]
        }
      })
      .state('modal', {
        parent: 'index',
        resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
          loadOcModal: ['$ocLazyLoad', '$injector', '$rootScope', function($ocLazyLoad, $injector, $rootScope) {
            // Load 'oc.modal' defined in the config of the provider $ocLazyLoadProvider
            return $ocLazyLoad.load({
              name: 'oc.modal',
              files: [
                'bower_components/bootstrap/dist/css/bootstrap.css', // will use the cached version if you already loaded bootstrap with the button
                'bower_components/ocModal/dist/css/ocModal.animations.css',
                'bower_components/ocModal/dist/css/ocModal.light.css',
                'bower_components/ocModal/dist/ocModal.js',
                'partials/modal.html'
              ]
            }).then(function() {
              $rootScope.bootstrapLoaded = true;
              // inject the lazy loaded service
              var $ocModal = $injector.get("$ocModal");
              $ocModal.open({
                url: 'modal',
                cls: 'fade-in'
              });
            });
          }],

          // resolve the sibling state and use the service lazy loaded
          setModalBtn: ['loadOcModal', '$rootScope', '$ocModal', function(loadOcModal, $rootScope, $ocModal) {
            $rootScope.openModal = function() {
              $ocModal.open({
                url: 'modal',
                cls: 'flip-vertical'
              });
            }
          }]
        }
      });

    // Without server side support html5 must be disabled.
    $locationProvider.html5Mode(false);

    // We configure ocLazyLoad to use the lib script.js as the async loader
    $ocLazyLoadProvider.config({
      debug: true,
      events: true,
      modules: [{
        name: 'gridModule',
        files: [
          'js/gridModule.js'
        ]
      }]
    });
  });
复制代码

 

lazy loading is more for projects that are huge with many people working on it, and you have tons and tons of files. Instead of concatenating every JavaScript file into a few megabytes loaded up front, it would make more sense to lazy load them.

But if you're just working on a small project it makes more sense just to concatenate everything and serve up one giant JavaScript file up front. That way you don't have to worry about files failing to load later on and things like that.

It's really a call on your end you have to make as to whether you need to lazy load or not. Typically I'd say you don't need to and you don't have to but if you're working on a large project and it's a huge load up front then lazy loading is something you should look into.

 

Read More: https://github.com/ocombe/ocLazyLoad/blob/master/examples/complexExample/js/app.js

posted @   Zhentiw  阅读(979)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示