Angular JS + Require JS 实现按需加载

先看下目录结构,为了方便配置将所有文件放在同一文件夹下,实际使用过程中建议归类文件:

Angular JS + Require JS 实现按需加载_第1张图片

1.index.html

DOCTYPE html>
 
<html lang="en">
 
<head>
 
  <meta charset="UTF-8">
 
  <title>require angularjstitle>
 
head>
 
<body>
 
<a href="#module1" rel="external nofollow" >module1a><br/>
 
<a href="#module2" rel="external nofollow" >module2a>
 
<div style="height: 30px;width: 100px">{{str}}div>
 
<div id="container" ui-view>div>
 
<script data-main="main.js" src="require.js" id="main">script>
 
body>
 
html> 

2.main.js

var config = {
 
  baseUrl: './',      //依赖相对路径
 
  paths: {          //如果某个前缀的依赖不是按照baseUrl拼接这么简单,就需要在这里指出
 
 
    angular: 'angular',
 
    app:'app',
 
    router:'angular-ui-router'
 
  },
 
  shim: {           //引入没有使用requirejs模块写法的类库。例如underscore这个类库,本来会有一个全局变量'_'。这里shim等于快速定义一个模块,把原来的全局变量'_'封装在局部,并导出为一个exports,变成跟普通requirejs模块一样
 
    'router': {
 
      deps: ['angular'],  //依赖什么模块
 
        
 
    },
 
    'angular': {
 
      exports: 'angular'
 
    }
 
  }
 
};
 
require.config(config);
 
// deps:['webapp']
 
require(['app','angular'],function(){
 
  angular.bootstrap(document, ['webapp'])//这里会去执行app.js这个文件
 
}) 

3.app.js

define(['router'], function () {
 
  var app = angular.module('webapp', ['ui.router']);
 
  app.config(
 
    function($stateProvider, $urlRouterProvider) {
 
      $urlRouterProvider.otherwise('module1');
 
      $stateProvider.
 
      state('module1', {
 
        url:"/module1",
 
        // controller: 'ctr1',     
 
        templateUrl: './module1.html',
 
        resolve: {
 
          loadCtrl: ["$q", function($q) {
 
            var deferred = $q.defer();

 
            require([
 
              './module1'
 
            ], function() { deferred.resolve(); });
 
            return deferred.promise;
 
          }]
 
        }
 
      })
 
      .state("module2",{
 
        url:"/module2",
 
        // controller: 'ctr2',
 
        templateUrl: './module2.html',
 
        resolve: {
 
          loadCtrl: ["$q", function($q) {
 
            var deferred = $q.defer();
 
         
            require([
 
              './module2'
 
            ], function() { deferred.resolve(); });
 
            return deferred.promise;
 
          }]
 
        }
 
      })
 
    });
 
  app.config(function($controllerProvider,$compileProvider,$filterProvider,$provide){
 
    app.register = {
 

 
      controller : $controllerProvider.register,
 
   
      directive: $compileProvider.directive,
 
      filter: $compileProvider.register,
 
      service: $provide.service
 
    };
 
  })
 
  return app;
 
}); 

4.module1.html

<div ng-controller="ctr1">

5.module2.html

<div ng-controller="ctr2">
  {{str}}
div> 

6.module1.js

define(['app'],function(app){
 
  app.register
 
    .controller('ctr1', function($scope){
 
      $scope.str = 'home page';
 
      console.log('page1')
 
    })
 
}) 

7.module2.js

define(['app'],function(app){
 
  app.register
 
    .controller('ctr2',function($scope){
 
      $scope.str = 'local page';
 
      console.log('page2')
 
    })
 
}) 

8.server.js  (node 服务)

var url  = require("url"),
    fs=require("fs"),
    http=require("http"),
    path = require("path");

http.createServer(function (req, res) {
    var pathname=__dirname+url.parse(req.url).pathname;
    if (path.extname(pathname)=="") {
        pathname+="/";
    }
    if (pathname.charAt(pathname.length-1)=="/"){
        pathname+="index.html";
    }

    fs.exists(pathname,function(exists){
        if(exists){
            switch(path.extname(pathname)){
                case ".html":
                    res.writeHead(200, {"Content-Type": "text/html"});
                    break;
                case ".js":
                    res.writeHead(200, {"Content-Type": "text/javascript"});
                    break;
                case ".css":
                    res.writeHead(200, {"Content-Type": "text/css"});
                    break;
                case ".gif":
                    res.writeHead(200, {"Content-Type": "image/gif"});
                    break;
                case ".jpg":
                    res.writeHead(200, {"Content-Type": "image/jpeg"});
                    break;
                case ".png":
                    res.writeHead(200, {"Content-Type": "image/png"});
                    break;
                default:
                    res.writeHead(200, {"Content-Type": "application/octet-stream"});
            }

            fs.readFile(pathname,function (err,data){
                res.end(data);
            });
        } else {
            res.writeHead(404, {"Content-Type": "text/html"});
            res.end("

404 Not Found

"); } }); }).listen(5000); console.log("Server running at localhost");

Angular JS + Require JS 实现按需加载_第2张图片

参考地址:https://www.jb51.net/article/115695.htm

 

转载于:https://www.cnblogs.com/Aaron-Lee/p/11447767.html

你可能感兴趣的:(javascript)