Bernd
Bernd

Reputation: 71

Executing JavaScript "in the background"

do you have any experiences with the following problem: JavaScript has to run hundreds of performance intensive function calls which cannot be skipped and causing the browser to feel crashed for a few seconds (e.g. no scrolling and clicking)? Example: Imagine 500 calls for getting an elements height and then doing hundreds of DOM modifications, e.g. setting classes etc. Unfortunately there is no way to avoid the performance intensive tasks. Web workers might be an approach, but they are not very well supported (IE...). I'm thinking of a timeout or callback based step by step rendering giving the browser time to do something in between. Do you have any experiences you can share on this?

Best regards

Upvotes: 2

Views: 154

Answers (3)

Bernd
Bernd

Reputation: 71

Here is what I can recommend in this case:

  1. Checking the code again. Try to apply some standard optimisations as suggested, e.g. reducing lookups, making DOM modifications offline (e.g. with document.createDocumentFragment()...). Working with DOM fragments only works in a limited way. Retrieving element height and doing complex formating won't work sufficient.
  2. If 1. does not solve the problem create a rendering solution running on demand, e.g. triggered by a scroll event. Or: Render step by step with timeouts to give the browser time to do something in between, e.g. clicking a button or scrolling.

Short example for step by step rendering in 2.:

var elt = $(...);
function timeConsumingRendering() {

    // some rendering here related to the element "elt"

    elt = elt.next();
    window.setTimeout((function(elt){
        return timeConsumingRendering;
    })(elt));
}
// start
timeConsumingRendering();

Upvotes: 0

adeneo
adeneo

Reputation: 318352

If your doing that much DOM manipulation, you should probably clone the elements in question or the DOM itself, and do the changes on a cached version, and then replace the whole ting in one go or in larger sections, and not one element at the time.

What takes time is'nt so much the calculations and functions etc. but the DOM manipulation itself, and doing that only once, or a couple of times in sections, will greatly improve the speed of what you're doing.

As far as I know web workers aren't really for DOM manipulation, and I don't think there will be much of an advantage in using them, as the problem probably is the fact that you are changing a shitload of elements one by one instead of replacing them all in the DOM in one batch instead.

Upvotes: 1

BalaKrishnan웃
BalaKrishnan웃

Reputation: 4557

Take a look at this topic this is some thing related to your question.

How to improve the performance of your java script in your page?

Upvotes: 2

Related Questions