简体   繁体   中英

Jquery CPU usage

I am using Jquery to make an image scroll across my page horizontally. The only problem is that it uses a serious amount of cpu usage. Up to 100% on a single core laptop in firefox. What could cause this???

Jquery

<script>
    jQuery(document).ready(function() {

    $(".speech").animate({backgroundPosition: "-6000px 0px"}, 400000, null);
    });

    </script>

CSS

.speech {
    /*position:fixed;*/
    top:0;
    left:0px;
    height:400px;
    width:100%;
    z-index:-1;
    background:url(/images/speech.png) -300px -500px repeat-x;
    margin-right: auto;
    margin-left: auto;
    position: fixed;
}

HTML

<div class="speech"></div>

It's using up CPU resources because you're asking the browser to repaint an image many times per second over a long period of time. That's not free.

In-case anyone is looking for a solution to high CPU usage when using jQuery animations (as I was) then it's worth noting that jQuery.fx.interval was added to jQuery 1.4.3 so you can control the animation interval rate.

Example of use (setting this to around 50-70 kept my animations smooth and I noticed CPU usage dropped down to about 10-20%):

jQuery.fx.interval = 50;

If this is a memory-cpu related issue then you can nullify the result of the jQuery function call. If your call returns a jQuery Object then after the call you can set it to null:

var tmp = $(".speech").animate({backgroundPosition: "-6000px 0px"}, 400000, null);
});
tmp = null;

Note: If this IS in ANY WAY related with the memory leak then it has to do with circular references and by setting to null you can break it.

Give it a try, i would like to know the results if you have the time to post.

实现此目的的最佳方法是使用诸如http://www.spritely.net/download/之类的插件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM