简体   繁体   中英

How do I optimize this Javascript function?

I have a procedure so that my top nav has a different style if the user is scrolled near the top of the page or farther down from:

/* Handle the changing of the top nav on page scroll */
window.onscroll = function ()
{
    if ($(window).scrollTop() > 150) // 150 pixels from top triggers scrolling
    {
        $('.navbar-default').addClass('scrolling');
    }
    else
    {
        $('.navbar-default').removeClass('scrolling');
    }
};

The problem is that I realize this is efficient because class of navbar-default is being added or removed a small number of times with respect to the number of times that onscroll is invoked. I also realized that I need to change an image in the nav depending on whether or not scrolling is happening, so I would then have essentially

/* Handle the changing of the top nav on page scroll */
window.onscroll = function ()
{
    if ($(window).scrollTop() > 150) // 150 pixels from top triggers scrolling
    {
        $('.navbar-default').addClass('scrolling');
        $('.navbar-default .navvar-brand img').attr('src','image1.jpg');
    }
    else
    {
        $('.navbar-default').removeClass('scrolling');
        $('.navbar-default .navvar-brand img').attr('src','image2.jpg');
    }
};

which is even more ridiculous. How can I fumigate this room full of code smell?

Here are some suggestions:

  • Place your curly braces on the same line as the function or you may run into situational problems with automatic semi colon insertion - Example
  • Use a sprite for the image instead - Tutorial
  • Toggle the class
  • Use css to change the toggle between images instead of changing the img source based on the class of the nav-default

     // Something like this... .nav-default { background-image: url('spriteimage.jpg'); background-repeat: no-repeat; height: // height of first image here; background-position: // position of first image here; } .nav-default.scrolling { height: // height of second image here; background-position: // position of second image here; } 

More advanced possibilities:

(I don't personally know if this boosts performance but you could try it)

  • Poll at a small interval (100ms) to check for the position of the scroll bar as opposed to checking every single time someone scrolls and then toggle the class
  • This will be less quick/responsive but will be more consistent (worst case: toggle the class every 100ms)

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