如何加快 jQuery 粘性页脚的加载时间

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

本文关键字:加载 时间 何加快 jQuery      更新时间:2023-09-26

所以我一直在为粘性页脚寻找一个可靠的解决方案。我发现一个在每个页面和每个浏览器中都能很好地工作;但是,加载然后生效需要一些时间。 有没有办法加快速度? 也许在页面加载之前加载它? 有人提到它可以设置为"onDOMready"而不是onLoad? 这有意义吗?

无论如何,这是我的代码:

<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>

如何使其加载速度更快?

不需要javascript(尽管它很有帮助)。这里最好的办法是利用奇妙的最小高度属性,而不是根据总文档高度进行计算。

.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;
  }

由于您的页面可能比这更复杂,如果您发现仅 css 中的min-height:100%不能产生所需的结果,您可能需要使用 javascript 进行设置。

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

演示阿拉@Nick

演示更多内容