수색…


프리로드보기

처음보기가 요청되면 일반적으로 Angular가 XHR 해당보기를 가져 오도록 요청합니다. 중간 크기 프로젝트의 경우보기 개수가 중요 할 수 있으며 응용 프로그램 응답 속도가 느려질 수 있습니다.

좋은 방법 중소 규모 프로젝트를 위해 모든 뷰를 한 번에 미리로드 하는 것입니다. 더 큰 프로젝트의 경우에는 의미있는 벌크로 집계하는 것이 좋지만 일부 다른 방법은로드를 분할하는 데 편리 할 수 ​​있습니다. 이 작업을 자동화하기 위해 Grunt 또는 Gulp 작업을 사용하면 편리합니다.

뷰를 미리로드하려면 $templateCache 객체를 사용할 수 있습니다. 이 객체는 서버에서 수신 한 모든 뷰를 각도로 저장합니다.

html2js 모듈을 사용하여 모든 뷰를 하나의 모듈 html2js 파일로 변환 할 수 있습니다. 그런 다음 모듈을 애플리케이션에 삽입해야합니다.

모든 뷰의 연결 파일을 만들려면이 작업을 사용할 수 있습니다.

module.exports = function (grunt) {
 //set up the location of your views here
 var viewLocation = ['app/views/**.html'];
 
 grunt.initConfig({
        pkg: require('./package.json'),
            //section that sets up the settings for concatenation of the html files into one file
            html2js: {
                        options: {
                            base: '',
                            module: 'app.templates', //new module name
                            singleModule: true,
                            useStrict: true,
                            htmlmin: {
                                collapseBooleanAttributes: true,
                                collapseWhitespace: true
                            }
                        },
                        main: {
                            src: viewLocation,
                            dest: 'build/app.templates.js'
                        }
                    },
            //this section is watching for changes in view files, and if there was a change, it will regenerate the production file. This task can be handy during development.
            watch: {
                views:{
                    files: viewLocation,
                    tasks: ['buildHTML']
                },
            }
        });
        
        //to automatically generate one view file
        grunt.loadNpmTasks('grunt-html2js');
        
        //to watch for changes and if the file has been changed, regenerate the file
        grunt.loadNpmTasks('grunt-contrib-watch');
        
        //just a task with friendly name to reference in watch
        grunt.registerTask('buildHTML', ['html2js']);
};

이러한 연결 방법을 사용하려면 다음 두 가지 사항을 변경해야합니다. index.html 파일에서 연결된보기 파일을 참조해야합니다

<script src="build/app.templates.js"></script>

파일에서 앱을 선언하는 곳에서 의존성을 삽입해야합니다.

angular.module('app', ['app.templates'])

당신이 ui-router 같은 대중적인 라우터를 사용한다면, 방법을 바꾸지 않고 템플릿을 참조하는 방법도 변하지 않습니다.

    .state('home', {
        url: '/home',
        views: {
            "@": {
                controller: 'homeController',
                //this will be picked up from $templateCache
                templateUrl: 'app/views/home.html'
            },
        }

    })

스크립트 최적화

JS 파일을 결합하여 축소하는 것이 좋습니다. 대규모 프로젝트의 경우 수백 개의 JS 파일이있을 수 있으며 각 파일을 서버와 별도로로드하기 위해 불필요한 대기 시간이 추가됩니다.

각도 축소를 위해 모든 기능에 주석을 달아야합니다. 그건 각도 의존성 주입에 필요한 적절한 minificaiton. (축소하는 동안 함수 이름과 변수의 이름이 바뀌므로 추가 작업을 수행하지 않으면 종속성 삽입이 중단됩니다.)

minificaiton 동안 $scopemyService 변수는 다른 값으로 대체됩니다. Angular dependency injection은 이름을 기반으로 작동하기 때문에 결과적으로 이러한 이름은 변경되어서는 안됩니다.

.controller('myController', function($scope, myService){
})

Angular는 배열 표기법을 이해합니다. 축소는 문자열 리터럴을 대체하지 않기 때문입니다.

.controller('myController', ['$scope','myService', function($scope, myService){
}])
  • 먼저 모든 파일을 끝까지 연결합니다.
  • 두 번째로 우리는 ng-annotate 모듈을 사용할 것이고, 이것은 minification을위한 코드를 준비 할 것이다.
  • 마지막으로 uglify 모듈을 적용 할 것입니다.

module.exports = function (grunt) {// 스크립트에서 코드를 재사용하기 위해 스크립트의 위치를 ​​설정합니다. var scriptLocation = [ 'app / scripts / *. js'];

 grunt.initConfig({
        pkg: require('./package.json'),
            //add necessary annotations for safe minification
         ngAnnotate: {
            angular: {
                src: ['staging/concatenated.js'],
                dest: 'staging/anotated.js'
            }
        },
        //combines all the files into one file
        concat: {
                js: {
                    src: scriptLocation,
                    dest: 'staging/concatenated.js'
                }
            },
        //final uglifying
        uglify: {
            options: {
                report: 'min',
                mangle: false,
                sourceMap:true
            },
            my_target: {
                files: {
                    'build/app.min.js': ['staging/anotated.js']
                }
            }
        },
        
        //this section is watching for changes in JS files, and if there was a change, it will regenerate the production file. You can choose not to do it, but I like to keep concatenated version up to date
        watch: {
            scripts: {
                files: scriptLocation,
                tasks: ['buildJS']
            }
        }
            
});

    //module to make files less readable
    grunt.loadNpmTasks('grunt-contrib-uglify');
    
    //mdule to concatenate files together
    grunt.loadNpmTasks('grunt-contrib-concat');
    
    //module to make angularJS files ready for minification
    grunt.loadNpmTasks('grunt-ng-annotate');
    
    //to watch for changes and if the file has been changed, regenerate the file
    grunt.loadNpmTasks('grunt-contrib-watch');
    
    //task that sequentially executes all steps to prepare JS file for production
    //concatinate all JS files
    //annotate JS file (prepare for minification
    //uglify file
     grunt.registerTask('buildJS', ['concat:js', 'ngAnnotate', 'uglify']);
};


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow