开发者

javascript - how to increase performance?

<script>
     function mySlide()
     {
        var myFx = new Fx.Slide('my-slide', {
            duration: 1000,
            transition: Fx.Transitions.Pow.easeOut
        });

        //Toggles between slideIn and slideOut twice:
        myFx.toggle().chain(myFx.toggle);

     }

     var interval = null;

     function clearTime()
     {
        $clear(interval);
     }

     function play()
     {
        interval = mySlide.periodical(1000);
     }
</script>
开发者_Python百科<div onclick="clearTime();"> stop </div>
<div onclick="play();"> play </div>
<img id="my-slide" src="http://lh5.ggpht.com/_8Nsej4QeRGg/TE5m5zRf4bI/AAAAAAAAAgo/pQGKPX8zn9c/gadget-01.jpg"/>

When I tried the above code with safari, the task manager in windows shows CPU utilisation of 30%-50%

When I put the above code in a full page with other html code, the utilisation is 60%-70%

So what is different? Why is the js faster on a clear page?


Because your script affects the page. I presume it adds something to the page, and then animates it. This requires the browser to:

  • search the elements on the page for the position to insert your new element(s) (called DOM traversal - not so much of a problem since you're using an ID, and not complex selectors)
  • calculate and re-render the page as elements get pushed around (called reflow - this is the most expensive)

Therefore in general, the more elements on your page, and the more CSS rules, the longer the DOM traversal and the reflow takes.

More on reflow:

  • http://code.google.com/speed/articles/reflow.html
  • http://www.mozilla.org/newlayout/doc/reflow.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜