如何在加载页面之前运行 jQuery?

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

How to run jQuery before loading page?

jqueryhtml

提问by Nips

I have many images on site and some scripts on it. But scripts can run only after loading whole page. How to accelerate this?

我在网站上有很多图片和一些脚本。但是脚本只有在加载整个页面后才能运行。如何加速?

回答by dqhendricks

$(document).ready(function() {
   //code here
});

will run a script when the document structure is ready, but before all of the images have loaded.

将在文档结构准备好但在所有图像加载之前运行脚本。

if you want to run script before the document structure is ready, just put your code anywhere.

如果您想在文档结构准备好之前运行脚本,只需将您的代码放在任何地方。

回答by Dave Newton

Load the images after the page loads?

页面加载后加载图像?

It may depends on what kind of jquery code you're trying to run--what specifically are you trying to do?

这可能取决于您尝试运行的 jquery 代码类型——您具体想做什么?

回答by campino2k

Use

$(document).ready(function() {
   //code here
});

and put the jQuery-Script tags at the end of the document.

并将 jQuery-Script 标签放在文档的末尾。

.readyfires when the DOM is ready (which does not mean that the images are already loaded).

.ready当 DOM 准备好时触发(这并不意味着图像已经加载)。

回答by swatkins

If your JavaScript does any work on your Dom elements, then you have to wait until the page loads.

如果你的 JavaScript 对你的 Dom 元素做了任何工作,那么你必须等到页面加载。

If you need to run the scripts before the image are loaded, you can always lazy load the images. That way you don't have to wait for the images to load.

如果您需要在加载图像之前运行脚本,您可以随时延迟加载图像。这样您就不必等待图像加载。

Lazy loading is basically loading the images through JavaScript, so you can control when they load.

延迟加载基本上是通过 JavaScript 加载图像,因此您可以控制它们何时加载。