什么是在HTML页面中加载Angularjs单个javascript文件的最佳方法

时间:2015-05-26 06:21:25

标签: angularjs

我的应用程序在客户端使用Angularjs,在服务器端使用Nodejs来构建单页应用程序。应用程序有很多视图和复杂,因此我有许多客户端指令和视图。以下是我的客户端Angularjs文件列表

1. App.js >> Defining the Angularjs app
2. ApplicationController.js >> This is global controller to handle the common stuff
3. ControllerView1.js, ControllerView2.js, ControllerView3.js, ControllerView4.js, ControllerView5.js, ControllerView6.js, ControllerView7.js, ControllerView8.js and many more
4. Directive1.js, Directive2.js, Directive3.js, Directive4.js, Directive5.js, Directive6.js, Directive7.js, Directive8.js, Directive9.js and many more 

目前我已在下面的部分加载了所有这些脚本

<script type="text/javascript" src="/js/vendor/angularjs/angular.min.js"></script>
<script type="text/javascript" src="/js/vendor/angularjs/angular-resource.min.js"></script>
<script type="text/javascript" src="/js/vendor/angularjs/angular-route.min.js"></script>
<script type="text/javascript" src="/js/vendor/angularjs/angular-sanitize.min.js"></script>
<script type="text/javascript" src="/js/vendor/angularjs/angular-animate.min.js"></script>
<!--App.js which is first file to be declared first -->
<script type="text/javascript" src="/js/application/App.js"></script>

<!--Factories -->
<script type="text/javascript" src="/js/application/factories/Resource.js"></script>


<!--Factories Implementation-->
<script type="text/javascript" src="/js/application/factories/implementation/ResourceImplementation.js"></script>

<!--Services -->
<script type="text/javascript" src="/js/application/utilities/HTTPResource.js"></script>
<script type="text/javascript" src="/js/application/services/ApplicationConstants.js"></script>
<script type="text/javascript" src="/js/application/services/ApplicationLoaderService.js"></script>
<script type="text/javascript" src="/js/application/services/FileUploadService.js"></script>

<!-- Application controllers -->
<script type="text/javascript" src="/js/application/controllers/ApplicationController.js"></script>
<script type="text/javascript" src="/js/application/controllers/AdminViewController.js"></script> 

<!--Directives -->
<script type="text/javascript" src="/js/application/directives/common/controls/LoadingScreen.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/FormTextBox.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/ViewFormTextBox.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/FormTextArea.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/FormCheckBox.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/ViewFormCheckBox.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/MenuPullDown.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/ViewDropdownBoxData.js"></script>
<script type="text/javascript" src="/js/application/directives/common/controls/DropdownBox.js"></script>
<script type="text/javascript" src="/js/application/directives/common/others/AddressViewer.js"></script>
<script type="text/javascript" src="/js/application/directives/common/others/AddressEditor.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/ImageUploader.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/ImageViewer.js"></script> 
<script type="text/javascript" src="/js/application/directives/common/media/ImageEditor.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/VideoPlayer.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/VideoUploader.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/VideoViewer.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/VideoEditor.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/ContentUploader.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/ContentViewer.js"></script>
<script type="text/javascript" src="/js/application/directives/common/media/HTMLContentEditor.js"></script>

<script type="text/javascript" src="/js/application/directives/common/others/ObjectTreeEditor.js"></script>  
<script type="text/javascript" src="/js/application/directives/common/others/ObjectArrayTreeEditor.js"></script>
<script type="text/javascript" src="/js/application/directives/common/others/ObjectTreeViewer.js"></script> 
<script type="text/javascript" src="/js/application/directives/common/others/ObjectArrayTreeViewer.js"></script>
<script type="text/javascript" src="/js/application/directives/common/others/ObjectViewer.js"></script> 
<script type="text/javascript" src="/js/application/directives/common/others/ObjectEditor.js"></script>
<script type="text/javascript" src="/js/application/directives/common/others/ObjectArrayEditor.js"></script> 
<script type="text/javascript" src="/js/application/directives/common/others/ObjectArrayViewer.js"></script>
<script type="text/javascript" src="/js/application/directives/common/others/ObjectFixedArrayEditor.js"></script> 
<script type="text/javascript" src="/js/application/directives/common/others/ObjectFixedArrayViewer.js"></script>

请注意;因为我在应用程序中有不同的视图因此理想情况下我不需要加载所有的js文件。我知道这不是加载js文件的理想方式。但是我不知道什么是正确的方法。我试图探索require.js,common.js和browserify.js但是无法为这个问题找到最佳解决方案。

请建议正确的方法来加载与Angularjs视图相关的js文件,以允许浏览器只为该视图所需的js文件添加。

3 个答案:

答案 0 :(得分:1)

为你的项目使用gulpjs任务运行器[结合js,less,css,html uglify&amp;缩小,支持少,sass,指南针,玉,haml,ejs编译器]或grunt

GulpGrunt

答案 1 :(得分:0)

使用延迟加载,在需要时加载js文件。

您可以结帐:https://oclazyload.readme.io/docs

答案 2 :(得分:0)

去年我使用以下方法在需要时使用以下库加载js / css / images

1. Webpack >> This is very beautiful module at build time. It helped to design the mapping of all resources for given view and load it.
2. oclazyload >> This module is at run time, it helps to load the Controller, Templates and related modules in lazy mode at run time
3. ui-router >> This router helps to adopt oclazyload.

以下是供您参考的示例代码。

Router.js

'use strict';
module.exports = {
    routes: function ($stateProvider, $urlRouterProvider) {
        //Set the default route
        $urlRouterProvider.otherwise('/myapp/dashboard');
        //Define routes for view   (Please make sure the most matched pattern is define at top)
        $stateProvider
                .state('dashboard', {
                    url: '/myapp/dashboard/:userid',
                    params: {
                        userid: {squash: true, value: null}
                    },
                    templateProvider: ['$q', function ($q) {
                            var deferred = $q.defer();
                            // note that the file name needs to be repeated in the require.ensure([...]) block 
                            // if you're going to use the uglifyJS plugin. It breaks otherwise.
                            require.ensure(['html!./../../../templates/partials/dashboard/dashboardView.html'], function (require) {
                                var template = require('html!./../../../templates/partials/dashboard/dashboardView.html');
                                deferred.resolve(template);
                            });
                            return deferred.promise;
                        }],
                    controller: 'dashboardViewController',
                    resolve: {
                        dashboard: ['$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
                                var deferred = $q.defer();

                                require.ensure([], function () {
                                    var app =require('./../webpackmodules/dashboard');
                                    $ocLazyLoad.load({
                                        name: 'MyApp.dashboard'
                                    });
                                    deferred.resolve(app.controller);
                                });

                                return deferred.promise;
                            }
                        ]
                    }
                })
                .state('clubview', {
                    url: '/myapp/clubview/:userid',
                    params: {
                        userid: {squash: true, value: null}
                    },
                    templateProvider: ['$q', function ($q) {
                            var deferred = $q.defer();
                            // note that the file name needs to be repeated in the require.ensure([...]) block 
                            // if you're going to use the uglifyJS plugin. It breaks otherwise.
                            require.ensure(['html!./../../../templates/partials/productpage/ClubPageView.html'], function (require) {
                                var template = require('html!./../../../templates/partials/productpage/ClubPageView.html');
                                deferred.resolve(template);
                            });
                            return deferred.promise;
                        }],
                    controller: 'ClubPageViewController',
                    resolve: {
                        product: ['$q', '$ocLazyLoad', function ($q, $ocLazyLoad) {
                                var deferred = $q.defer();

                                require.ensure([], function () {
                                    var app = require('./../webpackmodules/ClubPageViewPage');
                                    $ocLazyLoad.load({
                                        name: 'MyApp.BplatProductpage'
                                    });
                                    deferred.resolve(app.controller);
                                });

                                return deferred.promise;
                            }]
                    }
                })
                ;
    },
    html5mode: function ($locationProvider) {
        $locationProvider.html5Mode(true);
    }
};

仪表板webpack模块(webpackmodules / dashboard.js)

'use strict';
var app = angular.module('myApp.dashboard', ['ngResource', 'ngSanitize']);

//Add directives for dashboardview page
app.directive("product", ["$state", require("./../directives/dashboard/Product").getProduct]);
app.directive("userfilter", [require("./../directives/dashboard/UserFilter").getUserFilter]);
app.directive("compareuser", ["$location", require("./../directives/dashboard/compareuser").getcompareuser]);
app.directive("userquicklook", ["$location", require("./../directives/dashboard/userquicklook").getuserquicklook]);
app.directive("preloadimages", [require("./../directives/common/PreloadImages").getPreloadImages]);
//Add dashboardViewController which is specific to Dashboard page
app.controller('dashboardViewController', ['$scope', '$window', '$location', 'ApplicationLoaderService', 'ApplicationConstants', require("./../controllers/dashboardViewController").getdashboardViewController]);

module.exports = app;

App.js(第一个Angularjs文件)

'use strict';
// you need these two lines so that webpack can fetch the chunked bundles from the proper path
// or else it'll try to get them as a root relative path
if (location.protocol === 'https:') {
    __webpack_public_path__ = 'https://' + window.location.host + '/js/';
} else {
    __webpack_public_path__ = 'http://' + window.location.host + '/js/';
} 
var angular = require("angular");
require("angular-ui-router");
require("angular-resource");
require("angular-sanitize");
require("oclazyLoad");  

var Routers = require("./routers/Routers");
//load all common modules 
require('./webpackmodules/CommonAcrossPages');
//Get Angular Project module
var app = angular.module("myApp", ['ngResource', 'ui.router', 'ngSanitize', 'myApp.main', 'oc.lazyLoad']);


//Add client side routers
app.config(['$stateProvider', '$urlRouterProvider', Routers.routes]);
//Enable html5 mode
app.config(["$locationProvider", Routers.html5mode]);

的index.html

<!--Render different view as per requests -->        
<div class="myapp-container-wrapper" ui-view></div>