Angular + ocLazyLoad动态化加载脚本

 2015-12-26 18:25:29    AngularJs

在实际的开发中,由于功能众多产生的脚本文件也随之增多.这时候,我们要实现动态加载脚本来提升网页的响应速度,并且还要实现脚本缓存.现在市面上的加载器很多, 比如现在的require,但是相对来说require还是“弱”了一点,对angular来讲不是太完美,况且Angular本身就是模块化的东西,并不能完美的贴合. 所以,一个为angular量身定制的脚本加载器就出现了,小巧玲珑的它只有15KB15KB, 它就是ocLazyLoad

所有的文档在这里:猛戳这里

关于ocLazyLoad的文档很简单,大家看看就明白了。前提是你得先了解angular。

使用的方式大致三种:服务结合路由,指令,注入。下面的代码块一一对应

$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');
        }]
  }
});
<div oc-lazy-load="['js/testModule.js', 'partials/lazyLoadTemplate.html']">
  <!-- Use a directive from TestModule -->
  <test-directive></test-directive></div>
angular.module('MyModule', ['pascalprecht.translate', [ 
 '/components/TestModule/TestModule.js',  
 '/components/bootstrap/css/bootstrap.css',  
 '/components/bootstrap/js/bootstrap.js']
 ]);

在实际项目中最理想的方式就是结合路由来动态加载脚本,之前加载成功的脚本会在浏览器做缓存。

这里有一个完整的实例项目(戳这里)。

posted @ 2016-12-30 17:54  小小强学习网  阅读(201)  评论(0编辑  收藏  举报