Search code examples
javascriptjquerycssfooter

How do I speed up the load time of my jQuery sticky footer?


So I have been looking for a solid solution for a sticky footer for quite sometime. I found one that works well on every page and in every browser; however it takes some time to load and then take effect. Is there a way I can speed this up? Maybe load it before the page loads? Someone mentioned that it could be set to "onDOMready" instead of onLoad? Does that make sense?

Anyway, here is my code:

<script>
function positionFooter() { 
    var mFoo = $("#myfooter"); 
    if ((($(document.body).height() + 
            mFoo.height()) < $(window).height() && 
            mFoo.css("position") == "fixed") || 
            ($(document.body).height() < $(window).height() && 
            mFoo.css("position") != "fixed")) 
    { 
            mFoo.css({ position: "fixed", bottom: "0px" }); 
    } 
    else 
    { 
            mFoo.css({ position: "static" }); 
    } 
} 

    $(document).ready(function () { 
            positionFooter(); 
            $(window).scroll(positionFooter); 
            $(window).resize(positionFooter); 
            $(window).load(positionFooter); 
    });
</script>

<!--content --->

<div id="myfooter" style="width:100%;"><!--footer content--></div>

How do I make it load faster?


Solution

  • No javascript needed (though it is helpful). The best thing to do here is take advantage of the marvelous min-height property rather than calculate from total document height.

    html

      <div id="wrap">
           <div id="content">
           <footer></footer>
      </div>
    

    css

      html,body{
          height:100%;
      }
      #wrap{
           min-height:100%;
           position:relative;      
      }
    
      #content{
           padding-bottom:20px; // allow room for footer
      }
      footer{
           position:absolute;
           width:100%;
           bottom:0;
           left:0;
           height:20px;
      }
    

    As your page may be more complex than this, if you are finding that min-height:100% in css alone is not yielding the desired result, you may want to set in with javascript.

      $(document).ready(function(){
           var $window = $(window),
               $wrap = $('#wrap'),
               setMinHeight = function(){
                    $wrap.css('min-height',$window.height());
               };
               setMinHeight();
               $window.resize(setMinHeight);
      });
    

    DEMO al la @Nick

    DEMO with more content