AngularJS项目中如何实现按需加载js文件?

JavaScript018

AngularJS项目中如何实现按需加载js文件?,第1张

使用angularjs

+

requirejs就可以实现js文件的按需加载。

实现代码如下:

define(['app','navData'],

function

(app)

{

app.config(function($stateProvider,

$urlRouterProvider,

$controllerProvider,

navData){

app.registerController

=

$controllerProvider.register

app.loadJs

=

function(js){

return

function($rootScope,

$q){

var

def

=

$q.defer(),

deps=[]

angular.isArray(js)

?

(deps

=

js)

:

deps.push(js)

require(deps,function(){

$rootScope.$apply(function(){

def.resolve()

})

})

return

def.promise

}

}

$urlRouterProvider.otherwise('/memory')

angular.forEach(navData,

function(it){

var

st

=

it.state.split(/\./gi),

ctrlPath

=

'controllers/'

+

st[0],

ctrlName

=

'ctrl.'

+

st[0]

$stateProvider.state(st[0],{

url

:

'/'

+

st[0],

templateUrl

:

'tpls/'

+

st[0]

+

'.html',

controller

:

ctrlName,

resolve:{

deps:app.loadJs(ctrlPath)

}

})

})

})

})

angular2用webpack打包每次都只打包成单个mian文件,很大,例如页面中的关于我们,联系我们这样的页面,用户可能几乎不会打开,但是我们还是每次都要让用户加载,体验很不好,

这样就需要按需加载,当不长访问的页面,我们就单独打包成一个页面,当客户访问时,再去加载JS文件。

那么angular2如何进行按需加载呢?

我们使用webpack-toolkit,可以直接在git上看教程https://github.com/AngularClass/webpack-toolkit

angular2自己也支持异步加载,可以查看AsyncRoute的使用,github上查找会有很多使用例子

我写了个小demo,可以在dev分支中查看相关内容,https://github.com/lyt308012546/ng2-webpack-demo/tree/dev

// Install

npm install @angularclass/webpack-toolkit --save-dev

// app/about/about.ts

@Component({

selector: 'about',

template: '<h1>About</h1>'

})

export class About {}

// app/app.routes.ts

export const routes = [

{ path: '', component: Home },

{ path: 'about', component: 'About' }

]

// main.browser.ts

import {routes} from './app/app.routes'

import { provideWebpack } from '@angularclass/webpack-toolkit'

bootstrap(App, [

provideRouter(routes),

provideWebpack({

'About': require('es6-promise!./app/about')

})

])

// 以下是采用AsyncRoute进行异步加载

import { Component } from '@angular/core'

import { RouteConfig, RouterOutlet ,AsyncRoute } from '@angular/router-deprecated'

import { Router } from '@angular/router-deprecated'

import { SubRouteComponent } from './subroute'

@Component({

template: `

<h2>RouteConfig Demo</h2>

<button (click)="gotoDetail()">跳转</button>

<router-outlet></router-outlet>

`,

directives: [RouterOutlet],

})

@RouteConfig([

{path: '/',name: 'SubRouteComponent', component: SubRouteComponent, useAsDefault: true},

// 异步按需加载

new AsyncRoute({ path: '/detail', loader: () =>require('es6-promise!./routedetail')('RouteDetailComponent'), name: 'RouteDetailComponent' }),

])

export class RouteDemo {

constructor(

private router: Router) {}

gotoDetail(){

this.router.navigate(['RouteDetailComponent'])

}

}