Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New Coder
    Join Date
    Apr 2012
    Posts
    32
    Thanks
    20
    Thanked 0 Times in 0 Posts

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

  • #2
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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

  • #3
    Banned
    Join Date
    Oct 2012
    Posts
    81
    Thanks
    0
    Thanked 4 Times in 4 Posts
    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.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,519
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    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.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,519
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    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.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,519
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    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.

  • #7
    Banned
    Join Date
    Oct 2012
    Posts
    81
    Thanks
    0
    Thanked 4 Times in 4 Posts
    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

    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.

  • #8
    New Coder
    Join Date
    Apr 2012
    Posts
    32
    Thanks
    20
    Thanked 0 Times in 0 Posts
    guys thanks so much for helping me out. really appreciate your taking the time.

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,013
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    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.

  • #10
    Banned
    Join Date
    Oct 2012
    Posts
    81
    Thanks
    0
    Thanked 4 Times in 4 Posts
    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

    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.

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,013
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    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.

  • #12
    Banned
    Join Date
    Oct 2012
    Posts
    81
    Thanks
    0
    Thanked 4 Times in 4 Posts
    Quote Originally Posted by Philip M View Post
    Old Pedant was not pedantic enough!
    Agreed, as my example proved.

  • #13
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    And additionally this won't work
    Code:
    window.onload = doit;
    
    var doit = function() {
       ...
    }
    So function doit() is not equivalent to var doit = function()

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,519
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    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.

  • #15
    Banned
    Join Date
    Oct 2012
    Posts
    81
    Thanks
    0
    Thanked 4 Times in 4 Posts
    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.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •