Ways to improve AngularJS performance even with large number of DOM elements

前端 未结 6 463
自闭症患者
自闭症患者 2021-02-02 11:14

I\'m evaluating whether or not to use AngularJS for a web project, and I\'m worried about the performance for a feature I need to implement. I would like to know if there\'s a

6条回答
  •  一生所求
    2021-02-02 11:23

    Although an accepted answer exists allready, I think its important to understand why angularJS reacts so slow at the code you provided. Actually angularJS isnt slow with lots of DOM elements, in this case it's slow because of the ng-mouseover directive you register on each item in your list. The ng-mouseover directive register an onmouseover event listener, and every time the listener function gets fired, an ng.$apply() gets executed which runs the $diggest dirty comparision check and walks over all watches and bindings.

    In short words: each time an element gets hovered, you might consume e.g. 1-6 ms for the internal
    angular dirty comparision check (depending on the count of bindings, you have established). Not good :)

    Thats the related angularJS implementation:

    var ngEventDirectives = {};
        forEach('click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
            function(name) {
                var directiveName = directiveNormalize('ng-' + name);
                ngEventDirectives[directiveName] = ['$parse', function($parse) {
                return {
                    compile: function($element, attr) {
                        var fn = $parse(attr[directiveName]);
                        return function(scope, element, attr) {
                            element.on(lowercase(name), function(event) {
                                scope.$apply(function() {
                                    fn(scope, {$event:event});
                                });
                            });
                        };
                    }
                };
           }];
        }
    );
    

    In fact, for highlighting a hovered text, you probably would use CSS merely:

    .list-item:hover {
        background-color: yellow;
    }
    

    It is likely that with newer Angular Versions, your code as is, will run significantly faster. For angular version 1.3 there is the bind-once operator :: which will exclude once-binded variables from the digest loop. Having thousands of items, exluded will reduce the digest load significantly.

    As with ECMAScript 6, angular can use the Observe class, which will make the dirty comparisiion check totaly obsolete. So a single mouseover would result internally in a single event callback, no more apply or diggesting. All with the original code. When Angular will apply this, I dont know. I guess in 2.0.

提交回复
热议问题