document.ready vs document.onLoad

◇◆丶佛笑我妖孽 提交于 2019-12-21 02:51:12

问题


I am wondering which one is the right one to run the js code which calculates the height of vertical menu depending on the window height and sets it on time, not late, not early.

I am using document.ready but it is not really helping me with the issue, it is not setting sometimes, I have to reload the page, then it is working, but not on the first load.

How to solve this problem?

Here is my code:

$(document).ready(function(){
     var winh = document.body.clientHeight;
     var footer = document.getElementById('footer').offsetHeight;
     document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
     document.getElementById('sidebar').style.marginBottom = footer + 'px';

     $(window).resize(function(){
         var winh = document.body.clientHeight;
         var footer = document.getElementById('footer').offsetHeight;
         document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
         document.getElementById('sidebar').style.marginBottom = footer + 'px';
     });
});

回答1:


ready

When you run code when the document is ready, it means the DOM is loaded - but not things like images. If images will affect the height and width and the image tag has no width and height set, ready isn't the choice for you - otherwise it probably is.

onload

This includes images - so everything will be loaded. This means it fires a bit later.

both

var calculateSize = function () {
     var winh = document.body.clientHeight;
     var footer = document.getElementById('footer').offsetHeight;
     document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
     document.getElementById('sidebar').style.marginBottom = footer + 'px';
}

$(document).ready(function(){
    calculateSize();

     $(window).resize(calculateSize);
});

window.onload = calculateSize ;


来源:https://stackoverflow.com/questions/13420811/document-ready-vs-document-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!