Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: do I need to put calls to $("img").lazyload() in $(document).ready()?

I am using lazy load jquery plugin.

It tells me to put this in my code to activate it:

$("img").lazyload();

Do I have to put this in $(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>
like image 981
TIMEX Avatar asked Feb 28 '23 11:02

TIMEX


2 Answers

The demo page puts it in the $(document).ready(), except it uses the shorthand $( ) function to do it.

(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)

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. And if you're placing scripts in the HEAD, that's none of the images.

So, unless the library is somehow using the .live() function of JQuery, you need to put it in ready().

like image 182
kibibu Avatar answered Mar 24 '23 22:03

kibibu


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. 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.

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.

like image 29
David Thomas Avatar answered Mar 24 '23 23:03

David Thomas