Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-15-2012, 12:32 AM   PM User | #1
Redd4
New Coder

 
Join Date: Apr 2012
Posts: 32
Thanks: 20
Thanked 0 Times in 0 Posts
Redd4 is an unknown quantity at this point
question about the order script is written in

guys hey. im trying to learn javascript, and i have a question on something thats throwing me. it relates to the order in which its written. its probably very obvious and simple, but i cant see it.

in the code below, why is - window onload - at the bottom? i understand why the js links are at the bottom of a html page, but not why this seemingly reverse order is used in a .js file.
any and all advice appreciated, thanks for reading.

Code:
function preparePage() {
	document.getElementById("mainContent").onclick = function() {
        if ( document.getElementById("mainContent").className == "example") {
             document.getElementById("mainContent").className = "";
        } else {
           document.getElementById("mainContent").className = "example";
        }
	};
}

window.onload =  function() {
	preparePage();
};
Redd4 is offline   Reply With Quote
Old 11-15-2012, 12:49 AM   PM User | #2
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
In JavaScript the order of declarations is important, so functions should be defined before they are assigned to a variable or called. However, for your particular code-example, this requirement may be side-stepped because your call to preparePage() is within a closure, so you could switch the order and it should still work - try it. Good description here.

Personally I don't often encounter an issue with this as I always (where possible) define my functions before I call them. It is also a custom, or tradition, to define functions before the assignment to 'window.onload'.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 11-15-2012, 02:37 AM   PM User | #3
minder
Banned

 
Join Date: Oct 2012
Posts: 81
Thanks: 0
Thanked 4 Times in 4 Posts
minder can only hope to improve
Quote:
Originally Posted by Redd4 View Post
why is - window onload - at the bottom?
In this case the window.onload could be put anywhere in your script because all you are doing is assigning something to the browser window's onload event handler. That something (in this case an anonymous function) does not get executed until the browser triggers the window's onload event - ie. the page has finished loading completely, including downloading all the images and loading all the javascript. When the onload event is triggered, the event's handler (anonymous function) calls the preparePage() function and so preparePage() is executed after the window has finished loading.

If you did

Code:
window.onload = preparePage;  //this is a valid js statement
then the function preparePage would have to be defined before the window.onload because in this case you are assigning a reference to a function and the function needs to be first defined before you can assign references to it to anything.
minder is offline   Reply With Quote
Old 11-15-2012, 05:16 AM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,178
Thanks: 59
Thanked 3,995 Times in 3,964 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
And *IF* you followed Felgall's suggestion for writing modern JavaScript, it is all a non-issue.

You could write the page thus:
Code:
<html>
<body>
   <div id="mainContent"> ... </div>

<script type="text/javascript">
(
    function( )
    {
         
	document.getElementById("mainContent").onclick = 
            function() 
            {
                this.className = ( this.className == "example") ? "" : "example";
            }
    } /* end of anonymous master function */

)( ); /* self-invoke master function */
</script>
</body>
</html>
Notice that I also rewrote the onclick to be much simpler/more efficient. It could have been written that way in tho original.
__________________
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
Old 11-15-2012, 05:22 AM   PM User | #5
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,178
Thanks: 59
Thanked 3,995 Times in 3,964 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
Quote:
Originally Posted by minder View Post
If you did
Code:
window.onload = preparePage;  //this is a valid js statement
then the function preparePage would have to be defined before the window.onload because in this case you are assigning a reference to a function and the function needs to be first defined before you can assign references to it to anything.
Hmmm...

Code:
<html>
<head>
<script type="text/javascript">
window.onload = doit;

function doit( )
{
   document.body.style.backgroundColor = "lightblue";
}
</script>
</head>
<body>
REALLY?
<br/><br/>
Think again, Minder.

</body>
</html>
Functions do *NOT* have to be defined before you make a *REFERENCE* to them. JavaScript compiles all functions before it attempts actually USE the references.
__________________
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
Old 11-15-2012, 05:24 AM   PM User | #6
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,178
Thanks: 59
Thanked 3,995 Times in 3,964 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
And you can even do that ad nauseum:
Code:
<html>
<head>
<script type="text/javascript">
window.onload = doit;

function doit( )
{
   setTimeout( doit2, 5000 );
}

function doit2( )
{
   document.body.style.backgroundColor = "lightblue";
}
</script>
</head>
<body>
See?  Just wait a few seconds...
<br/><br/>
JavaScript is more flexible than you think.
</body>
</html>
__________________
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
Old 11-15-2012, 07:01 AM   PM User | #7
minder
Banned

 
Join Date: Oct 2012
Posts: 81
Thanks: 0
Thanked 4 Times in 4 Posts
minder can only hope to improve
Quote:
Originally Posted by Old Pedant View Post
JavaScript compiles all functions before it attempts actually USE the references.
Then how come when I run this in FF16 on a xampp server I get an error in the error console in FF saying

Quote:
referenceError: runMe is not defined
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <script type="text/javascript">
            window.onload=runMe;
        </script>
    </head>
    <body>
        <script type="text/javascript">
            function runMe(){
                alert('xxx');
            }   
        </script>
    </body>
</html>

Last edited by minder; 11-15-2012 at 07:06 AM..
minder is offline   Reply With Quote
Old 11-15-2012, 10:43 AM   PM User | #8
Redd4
New Coder

 
Join Date: Apr 2012
Posts: 32
Thanks: 20
Thanked 0 Times in 0 Posts
Redd4 is an unknown quantity at this point
guys thanks so much for helping me out. really appreciate your taking the time.
Redd4 is offline   Reply With Quote
Old 11-15-2012, 11:25 AM   PM User | #9
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by minder View Post
Then how come when I run this in FF16 on a xampp server I get an error in the error console in FF saying

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <script type="text/javascript">
            window.onload=runMe;
        </script>
    </head>
    <body>
        <script type="text/javascript">
            function runMe(){
                alert('xxx');
            }   
        </script>
    </body>
</html>

Because you have placed the call to runMe() in a separate script, and at the moment it is terminated by </script> that function does not yet exist.

Code:
<script type="text/javascript">
window.onload=runMe;
function runMe(){
alert('xxx');
}   
</script>
works just fine.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Philip M is offline   Reply With Quote
Old 11-15-2012, 11:35 AM   PM User | #10
minder
Banned

 
Join Date: Oct 2012
Posts: 81
Thanks: 0
Thanked 4 Times in 4 Posts
minder can only hope to improve
Quote:
Originally Posted by Philip M View Post
Because you have placed the call to runMe() in a separate script, and at the moment it is terminated by </script> that function does not yet exist.
Correct answer.

So old pedant saying

Quote:
JavaScript compiles all functions before it attempts actually USE the references.
is not strictly true which my example proved.

So as per his code
Code:
REALLY? <br/><br/> Think again, Minder.
the same applies to him

Last edited by minder; 11-15-2012 at 11:38 AM..
minder is offline   Reply With Quote
Old 11-15-2012, 11:44 AM   PM User | #11
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by minder View Post
Correct answer.

So old pedant saying

is not strictly true which my example proved.

So as per his code
Code:
REALLY? <br/><br/> Think again, Minder.
the same applies to him
Old Pedant was not pedantic enough!

Functions do *NOT* have to be defined before you make a *REFERENCE* to them. JavaScript compiles all functions within the same script before it attempts actually USE the references.

OK, bullant?
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
Philip M is offline   Reply With Quote
Old 11-15-2012, 11:51 AM   PM User | #12
minder
Banned

 
Join Date: Oct 2012
Posts: 81
Thanks: 0
Thanked 4 Times in 4 Posts
minder can only hope to improve
Quote:
Originally Posted by Philip M View Post
Old Pedant was not pedantic enough!
Agreed, as my example proved.
minder is offline   Reply With Quote
Old 11-15-2012, 11:53 AM   PM User | #13
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 531 Times in 525 Posts
devnull69 will become famous soon enough
And additionally this won't work
Code:
window.onload = doit;

var doit = function() {
   ...
}
So function doit() is not equivalent to var doit = function()
devnull69 is offline   Reply With Quote
Old 11-15-2012, 07:26 PM   PM User | #14
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,178
Thanks: 59
Thanked 3,995 Times in 3,964 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
Quote:
Originally Posted by devnull69 View Post
And additionally this won't work
Code:
window.onload = doit;

var doit = function() {
   ...
}
So function doit() is not equivalent to var doit = function()
Correct. When you assign a function to a variable, the rules are different.

But why do any of this? Use "unobtrusive JavaScript" as I showed in post #4 then you don't NEED to make any forward references. You don't even need the onload code to be its own function.

It's cleaner, simpler, and list to Felgall: He has a host of other reasons to do it that way.
__________________
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
Old 11-15-2012, 07:34 PM   PM User | #15
minder
Banned

 
Join Date: Oct 2012
Posts: 81
Thanks: 0
Thanked 4 Times in 4 Posts
minder can only hope to improve
Quote:
Originally Posted by Old Pedant View Post
But why do any of this?
It comes down to personal preference of how you want to code. Me, my preference is to put all the js in the <head> section unless it must go elsewhere.

I can't be bothered scrolling down to the bottom of web pages looking for javascript and unless you have a huge amount of javascript then any potential gain in page loading time by putting your js at the bottom of the page won't be noticeable to the naked eye.
minder is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:06 PM.


Advertisement
Log in to turn off these ads.