javascript document.ready 与 document.onLoad

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13420811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:43:43  来源:igfitidea点击:

document.ready vs document.onLoad

javascriptjqueryonloaddocument-ready

提问by doniyor

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.

我想知道哪个是运行 js 代码的正确方法,该代码根据窗口高度计算垂直菜单的高度并按时设置,不晚不早。

I am using document.readybut 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.

我正在使用document.ready但它并没有真正帮助我解决这个问题,它有时没有设置,我必须重新加载页面,然后它可以工作,但不是在第一次加载时。

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';
     });
});

回答by Fenton

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.

当您在文档准备好时运行代码时,这意味着 DOM 已加载 - 但不是图像之类的东西。如果图像会影响高度和宽度并且图像标签没有设置宽度和高度,ready 不是您的选择 - 否则它可能是。

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 ;