简体   繁体   English

jQuery:我需要在$(document).ready()中调用$(“img”)。lazyload()吗?

[英]jQuery: do I need to put calls to $(“img”).lazyload() in $(document).ready()?

I am using lazy load jquery plugin . 我正在使用lazy load jquery插件

It tells me to put this in my code to activate it: 它告诉我把它放在我的代码中来激活它:

$("img").lazyload();

Do I have to put this in $(document).ready() ? 我必须把它放在$(document).ready()吗? or can I just put it at the very top of the page: 或者我可以把它放在页面的最顶部:

<head>
<script type="text/javascript">
$("img").lazyload();

$(document).ready...{}

</script>
</head>

The demo page puts it in the $(document).ready(), except it uses the shorthand $( ) function to do it. 演示页面将它放在$(document).ready()中,除了它使用简写的$()函数来完成它。

(from the demo) (来自演示)

$( function() {
    $("img").lazyload({placeholder : "img/grey.gif"});
} );

(note that $() is an alias to the jQuery() function, which takes CSS selectors, HTML elements and also callbacks to run when the DOM loads) (注意,$()是一个别名到jQuery的()函数,该函数CSS选择器,HTML元素回调运行DOM负载时)

If you don't put it in the ready() function, then it may only affect images that are earlier in the page than your script. 如果您没有将它放在ready()函数中,那么它可能只影响页面中比您的脚本更早的图像。 And if you're placing scripts in the HEAD, that's none of the images. 如果你在HEAD中放置脚本,那就不是图像了。

So, unless the library is somehow using the .live() function of JQuery, you need to put it in ready(). 因此,除非库以某种方式使用JQuery的.live()函数,否则需要将它放在ready()中。

The way I understand it is that if you put it in the $(document).ready(...) the script won't run until the DOM has loaded. 我理解它的方式是,如果你把它放在$(document).ready(...) ,脚本将不会运行,直到DOM加载。 If you just put it in <script></script> tags in the head then the page will have to wait for the script to complete before the remainder of the DOM can load. 如果你只是将它放在head <script></script>标签中,那么页面必须等待脚本完成才能加载剩余的DOM。

If the script modifies the DOM this means it will run, do nothing, then the page will load (having not been affected by the $("img").lazyload() function. 如果脚本修改了DOM,这意味着它将运行,什么都不做,然后页面将加载(没有受到$("img").lazyload()函数的影响。

应该把它放在$(document).ready()中。

你需要把它放在里面因为它使用jQuery库。

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

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