angularjs 1.x lazyloading

本文介绍了 AngularJS 中 ocLazyLoad 的使用方法,包括模块、组件的懒加载方式,并详细展示了如何在路由中配合 ui-router 使用该插件确保视图加载前组件已经就绪。

https://oclazyload.readme.io/docs

  1. 安装好后直接使用
var myApp = angular.module("MyApp", ["oc.lazyLoad"]);
  1. 用来加载模块
myApp.controller("MyCtrl", function($ocLazyLoad) {
  $ocLazyLoad.load('testModule.js');
});
  1. 加载组件
    如果组件在独立的模块中就和模块差不多, 否则将要加载的组件应该是属于已定义好的模块

  2. live examples
    查看examples来了解更多的用法

在路由中的应用

$ocLazyLoad works well with routers and especially ui-router. Since it returns a promise, use the resolve property to make sure that your components are loaded before the view is resolved:

$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('js/AppCtrl.js');
    }]
  }
});

If you have nested views, make sure to include the resolve from the parent to load your components in the right order:

$stateProvider.state('parent', {
  url: "/",
  resolve: {
    loadMyService: ['$ocLazyLoad', function($ocLazyLoad) {
             return $ocLazyLoad.load('js/ServiceTest.js');
    }]
  }
})
.state('parent.child', {
    resolve: {
        test: ['loadMyService', '$ServiceTest', function(loadMyService, $ServiceTest) {
            // you can use your service
            $ServiceTest.doSomething();
        }]
    }
});

It also works for sibling resolves:

$stateProvider.state('index', {
  url: "/",
  resolve: {
    loadMyService: ['$ocLazyLoad', function($ocLazyLoad) {
             return $ocLazyLoad.load('js/ServiceTest.js');
    }],
        test: ['loadMyService', '$serviceTest', function(loadMyService, $serviceTest) {
            // you can use your service
            $serviceTest.doSomething();
        }]
    }
});

Of course, if you want to use the loaded files immediately, you don't need to define two resolves, you can also use the injector (it works anywhere, not just in the router):

$stateProvider.state('index', {
  url: "/",
  resolve: {
    loadMyService: ['$ocLazyLoad', '$injector', function($ocLazyLoad, $injector) {
      return $ocLazyLoad.load('js/ServiceTest.js').then(function() {
        var $serviceTest = $injector.get("$serviceTest");
        $serviceTest.doSomething();
      });
    }]
  }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值