jQuery "$(document).ready" 函数的替代方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12366410/
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-08-26 11:36:52  来源:igfitidea点击:

Alternative for "$(document).ready" function

jqueryasp.netfancyboxdocument-ready

提问by user1662341

I am using fancybox in an aspx page. The document ready function does not work in this page for a lightbox. Someone told me to write a new javascript code for loading the lightbox in that page.

我在aspx 页面中使用fancybox。文档就绪功能在此页面中不适用于灯箱。有人告诉我编写一个新的 javascript 代码来加载该页面中的灯箱。

回答by

  • Include jQuery.
  • Check network tab that you are not getting 404.
  • Check console that you are not getting "$ is unknown".
  • 包括 jQuery。
  • 检查网络选项卡,您没有收到 404。
  • 检查控制台您没有收到“$ 未知”。

Do stuff when DOM is ready.

当 DOM 准备好时做一些事情。

$(function(){
   // DOM Ready - do your stuff 
});

回答by Claudiu

Try this:

尝试这个:

document.addEventListener('DOMContentLoaded', function() {
   // ...
});

Works in modern browers and IE9+

适用于现代浏览器和 IE9+

回答by LasseValentini

You could use the standard js onload function to run if that's what your'e missing:

如果这就是你所缺少的,你可以使用标准的 js onload 函数来运行:

window.onload = function() {};

Do note that this might give you issues with libraries - I haven't investigated that.

请注意,这可能会给您带来图书馆方面的问题 - 我还没有调查过。

回答by Harshal Lonare

best ways is to use like this:

最好的方法是这样使用:

jQuery.noConflict();
(function($) {
  $(function() {
   // by passing the $ you can code using the $ alias for jQuery
   alert('Page: ' + $('title').html() + ' dom loaded!');
  });
})(jQuery);

回答by Mark Hymanson

I believe using the script defertag is the best solution. For example,

我相信使用脚本defer标签是最好的解决方案。例如,

<script src="demo_defer.js" defer></script>

More information at W3 Schools.

W3 学校了解更多信息。