How to prevent “A script on this page is causing Internet Explorer to run slowly” without changing MaxScriptStatements in the registry?

北慕城南 提交于 2019-12-06 03:51:35

Hardly anything you can do besides making your script "lighter". Try to profile it and figure out where the heaviest crunching takes place, then try to optimize those parts, break them down into smaller components, call the next component with a timeout after the previous one has finished and so on. Basically, give the control back to the browser every once in a while, don't crunch everything in one function call.

Generally a long running script is encountered in code that is looping.

If you're having to loop over a large collection of data and it can be done asynchronously--akin to another thread then move the processing to a webworker(http://www.w3schools.com/HTML/html5_webworkers.asp).

If you cannot or do not want to use a webworker then you can find your main loop that is causing the long running script and you can give it a max number of loops and then cause it to yield back to the client using setTimeout.

Bad: (thingToProcess may be too large, resulting in a long running script)

function Process(thingToProcess){     
    var i;
    for(i=0; i < thingToProcess.length; i++){
        //process here
    }
}

Good: (only allows 100 iterations before yielding back)

function Process(thingToProcess, start){    
    var i;
    if(!start) start = 0;
    for(i=start; i < thingToProcess.length && i - start < 100; i++){
        //process here
    }
    if(i < thingToProcess.length) //still more to process
        setTimeout(function(){Process(thingToProcess, i);}, 0);
}

Both can be called in the same way:

Process(myCollectionToProcess);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!