Search code examples
javascriptjqueryoptimizationuser-experiencepagespeed

How to optimize these jquery functions?


I'm working on a javascript intensive user-interface application. (At least it's intensive for me, it's my first serious javascript project).

I have a few jquery functions going whenever a div is rolled over or mouseout. For example there are some divs which are draggable objects, and so when they are mouseovered, the cursor must look ready to move. But my interface so slow that my boss thinks my code isn't working, when in fact it is, but it's just slow and so the user has to sometimes wait upto 2-3 seconds for the cursor to look as expected, or for a div to look as expected. Just an example. My code is something like below, I can't reproduce it entirely or properly since my company has copyrights on this, but just to give a clear idea of the way I'm doing things:

$.fn.extend({
    mouseoverBox: function() {
    return this.each(function() {
        var $this = $(this);   
                if(!$this.hasClass('ready')) 
                {   if($this.hasClass('activated'))
                    {
                        $this.removeClass('activated');
                    }
                    $this.addClass('ready');
                }
                var img_id = $this.children('.theimg').attr('id');
                //someitem.children('somechildren').remove();
                //someitem.append(somemenu div)
                //$this.draggable();
                //$this.resizable();
                if($this.hasClass('unlocked'))
                {
                    $this.draggable( "option", "disabled", false );
                    $this.resizable( "option", "disabled", false );
                }
                $this.bindUnlock();
            });
     }
// end mouseoverBox
});

Now this is just the mouseoverBox function, which is triggered like myBox.mouseoverBox(). on the mouse over event. Then of course this plugin is calling bindUnlock() which has simple operations like changing classes and adding classes to a menu. Also, before any mouseover, there's usually been a mouseout out of another div... so as you can see there's a lot of stuff happening. There aren't usually more than 10 interactive divs on at any one moment though. How can I optimize this kind of code? I haven't given every specific but trust me most of the relevant is pretty much just like this.

I've already gzipped my javascript, css, images and fonts. I also tried minifying using the Yahoo Compressor but it actually bloated one of my files instead of compressing it.


Solution

  • For the look and feel, why not just do this in the CSS using hover pseudo classes, e.g.:

    div.draggable:hover { 
        background:yellow;
        cursor:ponter;
    }
    

    That way all your class changing code could potentially be cut down.