Slow loading of AngularJS app in IE - add progress bar

前端 未结 5 1191
谎友^
谎友^ 2021-01-27 08:08

UPDATE1: Started using ngProgress, but not giving required effect in IE.
Final Update: Best solution found. See last answer below.


The AngularJS application ha

5条回答
  •  一生所求
    2021-01-27 08:59

    The problem got worse after reaching 1000+ fields. IE 11 took 3+ minutes to complete loading. I did further optimization and now the results are as follows for the time to complete loading:

    • IE11 : 1:30 (MM:SS)
    • Chrome: 00:20

    It is confirmed that the bottleneck is in the loop that will load the validation rules and apply them on the elements, then it will perform compile using $compile service.

    The validation rules are stored in DB using json format and retrieved using requiredFieldsPromise. See code sample below.

    Following is the new updated code for directive check-if-required:

    app.directive('checkIfRequired',  function($compile, $parse, $interpolate, $timeout, $q, BusinessLogic){
        return {
            priority: 100,
            terminal: true,
            restrict: 'A',
            require: '?^form',
            link: function (scope, el, attrs, ngForm) {
                var saveIsValidationRequired;
                var mainElmID = $interpolate(el[0].id)(scope);
                var resolvedPromise;
                var getChildren = function() {
                    var resultChildren;
                    //Return list of elements which were not compiled before 'compiled === undefined'
                    resultChildren = $(':input', el);
                    //Use code below just in case we want to extract the elements which are not compiled.
                    /*resultChildren = $(':input', el).filter(function(){
                        var result;
                        result = 
                            ($(this).attr('compiled') === undefined)
                        return result;
                    });*/
                    //Use $interpolate to get the final result for each ID...
                    for (var i=0; i < resultChildren.length; i++) {
                        if (resultChildren[i].id) {
                            resultChildren[i].id = $interpolate(resultChildren[i].id)(scope);
                        }
                    }
                    return resultChildren;
                }
                //User resolvedPromise when no such promise is available.
                resolvedPromise = $q.when('resolved');
                //Code improvement to make this directive more general
                //      Since this directive can be used from within an isolated scope directive such as 'photo-list-upload', then
                //      additional parameters are required to make it work properly.
                //      Make sure all required functions are defined or report warning.
                //      If the function is not defined within 'scope' it will be looked up from within 'BusinessLogic.getScope()'.
                //      If not found at all, default is used, and warning is reported.
                scope.getIsValidationRequired = scope.getIsValidationRequired || 
                                           (BusinessLogic.getScope().getIsValidationRequired) || 
                                           (console.warn("Directive 'check-if-required' element '%s' - function 'scope.getIsValidationRequired()' is not defined. It will always be false.", mainElmID), 
                                             function () {
                                               return false;
                                             }     
                                           );
                //The promise 'requiredFieldPromise' is used to retrieve list of validation rules from DB
                //Break Point Condition: scope.listData.photosFormName == "subjectPhotos"
                scope.stopExecValidations = scope.stopExecValidations || BusinessLogic.getScope().stopExecValidations || 
                            (console.warn("Directive 'check-if-required' element '%s' - function 'scope.stopExecValidations()' is not defined. Dummy function is used instead.", mainElmID),
                              function () {
                                //Dummy
                              }
                            );
                scope.requiredFieldsPromise = 
                    scope.requiredFieldsPromise || (BusinessLogic.getScope().requiredFieldsPromise) || 
                    (console.warn("Directive 'check-if-required' element '%s' - function 'scope.requiredFieldsPromise' is not defined. Resolved promise will be used.", mainElmID),
                     resolvedPromise);
                //If needed, stop validation while adding required attribute
                //Save current flag value
                saveIsValidationRequired = scope.getIsValidationRequired();
                scope.stopExecValidations();
                //remove the attribute `check-if-required` to avoid recursive calls
                el.removeAttr('check-if-required');         
                // NE-2808 - Define function to add validation message using $watch
                //                As soon as an error is detected, then 'title' will be set to the error
                //                Parameters:
                //                  - ngForm: Angualr Form 
                //                  - elm: The HTML element being validated
                //                  - errAttr: the name of the error attribute of the field within ngForm:
                //                      ngFormName.FieldName.$error.errAttributeName
                //                  - errMsg: The error message to be added to the title 
                //                  - msgVar1: optional substitution variable for the error message
                var addValidationMessage = function (ngForm, elm, errAttr, errMsg, msgVar1) {
                    //Use $timeout to ensure validation rules are added and compiled.
                    //After compile is done then will start watching errors
                    $timeout(function(){
                        var elmModel;
                        var ngModelName="";
                        //Get the name of the 'ng-model' of the element being validated
                        elmModel = angular.element(elm).controller('ngModel');
                        if (elmModel && elmModel.$name) {
                            ngModelName = elmModel.$name;
                        }
                        if (!ngModelName) {
                            ngModelName = angular.element(elm).attr('ng-model');
                        }
                        if (ngModelName) {
                            scope.$watch(ngForm.$name + '.' + ngModelName + '.$error.' + errAttr,
                                function (newValue, oldValue){
                                    //console.log("elm.id =", elm.id);
                                    //The validation error message will be placed on the element 'title' attribute which will be the field 'tooltip'.
                                    //newValue == true means there is error
                                    if (newValue) {
                                        var msgVar1Val;
                                        //Perform variable substitution if required to get the final text of the error message.
                                        if (msgVar1) {
                                            msgVar1Val = scope.$eval(angular.element(elm).attr(msgVar1));
                                            errMsg = errMsg.format(msgVar1Val);
                                        }
                                        //Append the error to the title if neeeded
                                        if (elm.title) {
                                            elm.title += " ";
                                        } else {
                                            elm.title = "";
                                        }
                                        elm.title += errMsg;
                                    } else {
                                        //Remove the error if valid.
                                        //child.removeAttribute('title');
                                        if (elm.title) {
                                            //Remplace the error message with blank.
                                            elm.title = elm.title.replace(errMsg, "").trim();
                                        }
                                    }
                                });
                        } else {
                            //console.warn("Warning in addValidationMessage() for element ID '%s' in ngForm '%s'. Message: 'ng-model' is not defined.", elm.id, ngForm.$name)
                        }
                    }, 1000);       
                }             
                function doApplyValidation(scope, el, attrs, ngForm) {
                    var children;
                    children = getChildren();
                    mainElmID = $interpolate(el[0].id)(scope);
                    validationList=formView.getRequiredField();
                    for (var subformIdx=0; subformIdx < Object.keys(validationList).length; subformIdx++) {
                        var keySubform = Object.keys(validationList)[subformIdx];
                        var subform = validationList[keySubform];
                        var lastFieldID;
                        lastFieldID = Object.keys(subform)[Object.keys(subform).length-1];
                        for (var childIdx=0; childIdx < Object.keys(subform).length; childIdx++) {
                            var childID = Object.keys(subform)[childIdx];
                            var validObjects;
                            var childElm;
                            var child;
                            var elmScope;
                            var elmModel;
                            childID = childID.trim();
                            //Find the element with id = childID within the 'el' section.
                            //Use 'getChildren()' since the result list has ID values which are interpolated.
                            childElm = children.filter('#'+childID);
                            if (childElm.length) {
                                //Validation rule for 'childID': related element was found, and now will apply validation rule.
                                validObjects = subform[childID];
                                child = childElm.get(0);
                                elmScope = angular.element(child).scope() || scope;
                                elmModel = angular.element(child).controller('ngModel');
                                var maxlength = scope.$eval(angular.element(child).attr('ng-maxlength'));
                                //var errMsg = ("Number of characters entered should not exceed '{0}' characters.").format(maxlength);
                                // NE-2808 - add validation message if length exceeds the max
                                var errMsg = "Number of characters entered should not exceed '{0}' characters.";
                                addValidationMessage(ngForm, child, 'maxlength', errMsg, 'ng-maxlength');                           //Check if the element is not in "Required" list, and it has an expression to control requried, then
                                //... add the attribute 'ng-required' with the expression specified to the element and compile.
                                if (!angular.element(child).prop('required') && child.attributes.hasOwnProperty("check-if-required-expr")) {
                                    console.error("Unexpected use for attribute 'check-if-required-expr' in directive 'check-if-required' for element ID '%s'. Will be ignored.", childID);
                                }
                                if (validObjects === "") {
                                    //This means the field is required
                                    angular.element(child).attr('ng-required', "true");
                                }
                                else if (angular.isArray(validObjects)) {
                                    //This means that there is a list of validation rules
                                    for (var idx=0; idx < validObjects.length; idx++) {
                                        var validObject = validObjects[idx];
                                        var test = validObject.test || "true"; //if not exist, it means the rule should always be applied
                                        var minLenExp = validObject.minlen;
                                        var maxLenExp = validObject.maxlen;
                                        var isRequiredExp = validObject.required || false;
                                        var readonlyExp = validObject.readonly || null;
                                        var pattern = validObject.pattern || "";
                                        var isCAPostalCode = validObject.isCAPostalCode || false;
                                        isRequiredExp = angular.isString(isRequiredExp)?isRequiredExp:isRequiredExp.toString();
                                        if (test) {
                                            var testEval = scope.$eval(test, elmScope);
                                            if (testEval) {
                                                if (minLenExp) {
                                                    angular.element(child).attr('ng-minlength', minLenExp);
                                                }
                                                if (maxLenExp) {
                                                    angular.element(child).attr('ng-maxlength', maxLenExp);
                                                }
                                                //If the "required" expression is '*skip*' then simply skip.
                                                //If '*skip*' is used, this means the required validation is already defined in code
                                                //and no need to replace it.
                                                if (isRequiredExp && isRequiredExp != '*skip*') {
                                                    angular.element(child).attr('ng-required', isRequiredExp);
                                                }
                                                // NE-3211 - add readonly validation
                                                if (readonlyExp && readonlyExp != '*skip*') {
                                                    angular.element(child).attr('ng-readonly', readonlyExp);
                                                }
                                                if (pattern) {
                                                    angular.element(child).attr('ng-pattern', pattern);
                                                }
                                                if (isCAPostalCode) {
                                                    angular.element(child).attr('ng-pattern', "/^([A-Z]\\d[A-Z] *\\d[A-Z]\\d)$/i");
                                                    // NE-2808 - add validation message if postal code does not match the RegEx
                                                    addValidationMessage(ngForm, child, 'pattern', "Invalid postal code.");
                                                }
                                                //delete the validation rule after it is implemented to improve performance
                                                delete subform[childID]
                                                //TODO: Apply only the first matching validation rule
                                                //      May required further analysis if more that one rule will be added.
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        } // for loop
                    } // for loop
                    //After done processing all elements under 'el', compile the parent element 'el'.
                    $compile(el, null, 100)(scope);
                    //If saved flag value is true, enable back validation
                    if (saveIsValidationRequired) {
                        scope.startExecValidations();
                    }
                }
                function applyValidationTimeout() {
                    //Execute 'doApplyValidation()' in the next cycle, to ensure the child elements have been rendered.
                    $timeout(function(){
                        //console.log('applyValidationTimeout', mainElmID);
                        doApplyValidation(scope, el, attrs, ngForm);                    
                    }, 100)
                }
                scope.requiredFieldsPromise.then(function(success) {
                    //Apply validation when the Required Fields and Validation Rules have been loaded.
                    applyValidationTimeout();
                }, function(prmError){
                    console.warn("Error occured in 'check-if-required' directive while retrieving 'requiredFieldsPromise' for element '%s': %s", mainElmID, prmError);
                });
            }
        }
    
    });
    

    Though the performance now is much better now, however, I realized that the problem is in using $compile, therefore, I am now thinking to find a solution by avoiding use of $compile. Here is my plan.

    Instead of modifying the element HTML by adding 'ng-required' directive, then compile, instead, I can skip HTML and use the ngModel.NgModelController of the related HTML Element, then access the $validators to perform validation using code. If you read the code above, you will see that I have already accessed the ngModel.NgModelController for each element in variable elmModel. I think this variable will provide access to $validators which can be used to add validation to the element. Since the rules are now available in validationList variable, I will write a function to perform validation by looking up this list and apply the available validation on-the-fly.

    This will be the improvement in the future sprints.

    If you have any feedback, please let me know.

    Tarek

提交回复
热议问题