简体   繁体   English

页面加载完成后运行代码的正确方法是什么

[英]What is the proper way to run code after page has done loading

I have page X. 我有第X页。

in X, i put in the head tag, a script tag. 在X中,我放入了head标签,一个脚本标签。 the script needs to scan the body once the body has done rendering. 一旦身体完成渲染,脚本需要扫描身体。

I tried jQuery.ready() but it is not called! 我试过jQuery.ready()但它没有被调用! Can it be that the DOM is ready before the script is starting to run? 在脚本开始运行之前,DOM是否已准备就绪? what can I do? 我能做什么?

thanks 谢谢

jQuery.ready() isn't a function (well, not the handler you want anyway), what you want is jQuery(document).ready() , like this: jQuery.ready()不是一个函数(好吧,不是你想要的处理程序),你想要的是jQuery(document).ready() ,如下所示:

jQuery(document).ready(function() {
  alert("DOM is ready!");
});

Or, the shorter form: 或者,更短的形式:

jQuery(function() {
  alert("DOM is ready!");
});

Did you try calling ready like this: 您是否尝试过这样的准备:

<script type="text/javascript">
$(document).ready(function() {
     //do things..
});
</script>

You may need to define what you mean by "done loading." 您可能需要通过“完成加载”来定义您的意思。 The .ready() function in jQuery, which is most often properly called as $(document).ready(handler); jQuery中的.ready()函数,通常被正确地称为$(document).ready(handler); , should indeed be invoked as soon as the DOM is finished loading. ,确实应该在DOM完成加载后立即调用。 (If it's not being invoked, I suspect there's an error in your code or jQuery isn't loaded.) (如果没有被调用,我怀疑代码中有错误或者没有加载jQuery。)

However, there is often an intuitive confusion between the DOM being loaded and the "page" being loaded. 但是,正在加载的DOM和正在加载的“页面”之间经常存在直观的混淆。 The former is all jQuery really cares (or knows) about, and is not dependent on loading external content referenced by the DOM (such as images, style sheets, etc.). 前者是jQuery真正关心(或知道)的全部,并且不依赖于加载DOM引用的外部内容(例如图像,样式表等)。

According to this documentation , all three of the following syntaxes are equivalent: 根据此文档 ,以下所有三种语法都是等效的:

* $(document).ready(handler)
* $().ready(handler) (this is not recommended)
* $(handler)

And this code provides a simple example: 这段代码提供了一个简单的例子:

<!DOCTYPE html>
<html>
<head>
  <style>p { color:red; }</style>
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
  <script>
  $(document).ready(function () {
  $("p").text("The DOM is now loaded and can be manipulated.");
});
  </script>

</head>
<body>
  <p>Not loaded yet.</p>

</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM