Home > Web Front-end > JS Tutorial > body text

Analysis of AngularJS Compression JS Techniques

高洛峰
Release: 2016-12-07 13:57:45
Original
1093 people have browsed it

The examples in this article describe the operation techniques of AngularJS compressing JS. Share it with everyone for your reference, the details are as follows:

Most web projects will compress the js code when publishing, in order to reduce the size of the js file and save some traffic.

The principle is very simple, which is to rename parameters, some variable names and functions.

But there are exceptions to this way of working in AngularJS applications.

Since AngularJS’s dependency injection is injected based on parameter names, obviously, renaming parameters will destroy this mechanism.

If no special processing is performed, after compression (minify), such an error will occur during execution

Unknown provider: aProvider<-a

The official explanation for this error is: The dependent service cannot be found

That is to say, this kind of dependency injection will cause errors.

Fortunately, AngularJS has a built-in standard mechanism to handle this problem.

The simplest and most common way is to use an array instead of a function. For example:

.controller(&#39;RegisterCtrl&#39;, [&#39;$scope&#39;, &#39;$interval&#39;, &#39;$timeout&#39;, function ($scope, $interval, $timeout) {
  //do something
}]);
Copy after login

The last element of the array is always a function, and the first few parameters are all strings, corresponding to the parameters in this function.

Another form is the so-called Annotation method. Such as

var objCtrl = function($scope, $timeout, $interval){
  // do something
}
//给objCtrl函数增加一个$inject属性,它是一个数组,定义了需要被注入的对象
objCtrl.$inject = [&#39;$scope&#39;, &#39;$interval&#39;, &#39;$timeout&#39;];
Copy after login

The form of dependency injection here is not limited to Controller. Everything that requires DI (directive, factory, services, etc. for dependency injection) can use these two methods.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template