Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have function that I need to run on window load as well as window resize and I was wondering how can I make my code more efficient.

Here is my current code:

jQuery(window).resize(homeSliderAdjust);

var windowWidth = jQuery(window).width();


if (windowWidth < 750) {
    var hmLeft = jQuery('.page-home #slides .left').outerHeight();
    var hmRight = jQuery('.page-home #slides .right img').outerHeight();
    var hmSliderHeight = hmLeft + hmRight;
    jQuery(".page-home #slides").css("height", hmSliderHeight);
    jQuery(".page-home #hero").css("height", hmSliderHeight);

  }

function homeSliderAdjust(){
    var windowWidth = jQuery(window).width();
    if (windowWidth < 750) {
      var hmLeft = jQuery('.page-home #slides .left').outerHeight();
      var hmRight = jQuery('.page-home #slides .right img').outerHeight();
      var hmSliderHeight = hmLeft + hmRight;
      jQuery(".page-home #slides").css("height", hmSliderHeight);
      jQuery(".page-home #hero").css("height", hmSliderHeight);
    }
  }
share|improve this question

migrated from stackoverflow.com Jan 5 at 14:18

This question came from our site for professional and enthusiast programmers.

2 Answers 2

Basic, easy 80/20 performance optimizations:

share|improve this answer

I would split the jQuery selectors into vars. So jQuery doesn't need to look for the elements in DOM every time you resize.

var leftObj = jQuery('.page-home #slides .left');
var rightObj = jQuery('.page-home #slides .right img');
var pageSlides = jQuery(".page-home #slides");
var heroObj = jQuery(".page-home #hero");

var windowWidth = jQuery(window).width();
if (windowWidth < 750) {
   // I would do that as well as soon as it does the same as the code below
   homeSliderAdjust();     
}

function homeSliderAdjust(){
    var windowWidth = jQuery(window).width();
    if (windowWidth < 750) {
      var hmLeft = leftObj.outerHeight();
      var hmRight = rightObj.outerHeight();
      var hmSliderHeight = hmLeft + hmRight;
      pageSlides.css("height", hmSliderHeight);
      heroObj.css("height", hmSliderHeight);
    }
}

jQuery(window).resize(homeSliderAdjust);

This is a good article about jQuery selectors caching

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.