JQuery code placement proposal

I know this will sound like a silly question, but since I am learning jQuery as an example, I found that the placement of scripts and functions varies greatly from example to example. The thing is, somewhere I read that the .onReady function should be located below everything else to ensure that the entire DOM is actually ready and something like that.

The question is simply this, besides the truncated script tags, is there a best practice of where the jquery should be located in the PHP file? What about one-time inline scripts? Sorry for the naive nature of this, but I would try these examples โ€œcorrectlyโ€ as I figured out how to put it all together.

There seem to be some very insightful people on this site, so well in advance for any guidance! :)

Apparently, it was not as stupid as I thought - thanks to everyone for understanding - I feel a little more clarity about what I was trying to understand in the big picture.

+5
source share
4 answers

AFAIK, no .onReady

Perhaps you mean $(document).ready()?

The point .ready()must wait until the item is ready. In this case, the document. Thus, nothing of this will be done until the document is ready. So you can place this anywhere.

As for where you are referencing JS files, you want to do this at the bottom of the document for performance reasons:

http://developer.yahoo.com/performance/rules.html

+8
source

PHP, onReady " , DOM " !

, , , .

:

$('#foo').val() // undefined - the DOM isn't ready yet.

$(document).ready(function(){
    $('#foo').val() // bla - the DOM is ready now.
});
<input id="foo" value="bla" />

Live DEMO

, $(callbackFunction) $(document).ready(callbackFunction);

ready docs

+4

<script type="text/javascript"></script> <body> . , .

+2

JavaScript. , .

:

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

:

$(function() {
 // Put your code here.
});

, , </body> .

0

All Articles