joy
joy

Reputation: 3707

What is best way to load Angularjs individual javascript files in HTML page

My application is using Angularjs at client side and Nodejs at server side to build Single Page Application. Application has many views and complex therefore I have many client side directives and views. Following are my list of client side Angularjs files

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 

Currently I have loaded all these scripts in section as below

<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>

Please note; since I have different view in application therefore ideally I am not require to load all the js files. I know this is not the ideal way to load js files. However I don't know what is correct way. I tried to explore the require.js, common.js and browserify.js however not able to map the best solution for this problem.

Please advice the correct way to load the js files related to Angularjs view to allow browser to laod the js files required for that view only.

Upvotes: 1

Views: 1904

Answers (3)

joy
joy

Reputation: 3707

Last year I used following approach to load the js/css/images when it is required using following library

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.

Following is sample code for your reference.

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);
    }
};

dashboard webpack module (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 (First Angularjs file)

'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>

Upvotes: 0

Rahul Sagore
Rahul Sagore

Reputation: 1658

Use Lazy load, to load the js file when required.

You can checkout: https://oclazyload.readme.io/docs

Upvotes: 0

Alex Kashin
Alex Kashin

Reputation: 575

use gulpjs task runner for ur projects [combine js,less,css,html uglify & minify, support less,sass, compass, jade, haml, ejs compilers] or grunt

Gulp or Grunt

Upvotes: 1

Related Questions