View Single Post
Old 12-20-2012, 09:14 PM   PM User | #16
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,237
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
> why is it that this script only works when placed below the content in the body,

Clearly you haven't been reading Felgall's posts...or his website.

Anyway, *NO* JavaScript can use document.getElementById or getElementsByClassName or any of the other "get" methodologies if it is invoked *BEFORE* the browser has laid out all the HTML that defines the looked-for elements.

In the traditional (also known as "old fashioned" or, per Felgall, "obsolete") placement of JS in the <head> of the page, you have to use various techniquest to make sure the JS does not even TRY to execute until after the page is loaded.

Typically, that means you put all the JS in some function (e.g., function initializePage( ) ... ) and then do either window.onload = initializePage; or <body onload="initializePage()">

It works. But isn't it kind of clumsy? Doesn't it make more sense to simply put the JS at the *END* of the page, so that all the HTML is already laid out and ready to be used?

Oh...and putting it at the end makes the HTML load faster, too, in many circumstances.

Anyway, go find a post by Felgall and then follow the link to his website, etc.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote