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 19
  1. #1
    Regular Coder
    Join Date
    Sep 2011
    Posts
    193
    Thanks
    147
    Thanked 0 Times in 0 Posts

    Unhappy Inserting Javascript Code in between the <BODY> tags

    Thread closed, problem solved.

    Inserted javascript body text into Head section and called the window.onload()
    Last edited by jason_kelly; 06-22-2012 at 08:53 PM.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by jason_kelly View Post
    Thread closed, problem solved.

    Inserted javascript body text into Head section and called the window.onload()
    So you did it WRONG.

    JavaScript should almost always go immediately before the </body> tag at the end of the page. It only goes in the head when testing whether to display the page or not.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    Quote Originally Posted by felgall View Post
    So you did it WRONG.

    JavaScript should almost always go immediately before the </body> tag at the end of the page. It only goes in the head when testing whether to display the page or not.
    That it is recommended to put the <script> as the last thing in the <body>, does not make the alternative placement WRONG.

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Lerura View Post
    That it is recommended to put the <script> as the last thing in the <body>, does not make the alternative placement WRONG.
    It depends on whether you define a location that both slows down the rendering of the page AND delays the running of the script longer than necessary as wrong and whether you want to encourage visitors to stay or to leave.

    You can speed up both the rendering of the web page and the running of the script by placing it at the bottom and not using onload. That way more visitors will actually stay long enough for your page to load.

    It is WRONG to make your page load slower than it needs to if you actually want visitors on your site.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #5
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    If your page is of a kind where the viewer uses quite some time to read the page, before they do an action that calls the script, then it would be better to have the script load last, as it then can load while the users read the page.

    On the other hand, if the page is of a kind where users often will do action as soon as they can see where to click and maybe even before all content is rendered, then I will say that you should put the scripts at the top.
    In this case "rendered" means "ready to use".

    If you have some scripting that is automatically run during the loading, such as onloads, then it would save some code by executing the lines directly, instead of including it in a function that you later call. In other words: code it where it is needed.

    function that are only called by user action, should IMO be placed at the top, in order to keep them separated from the html-coding.

    But in the end: your page have to be quite heavy before the placement of the script makes a significant difference.

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Lerura View Post
    On the other hand, if the page is of a kind where users often will do action as soon as they can see where to click and maybe even before all content is rendered, then I will say that you should put the scripts at the top.
    Since you need to wait for the HTML to be loaded before your JavaScript can attach itself to that HTML in order to do anything (assuming that you don't jumble the JavaScript into the HTML) then placing it immediately after the last tag it needs to reference in the body of the page is the SOONEST it can run. Placing it just before the </body> may cause a microsecond or so additional delay. Placing it in the head may delay it for minutes (depending on how long the rest of the page takes to load).

    If you try to run the JavaScript before the tag is loaded then it will not work so you can't run it in the head - you'd have to wait for the documentReady or load event to trigger before being able to attach it from in the head of the page. documentReady runs just after the script would run if attached at the bottom of the body and load can run much later - but not all browsers recognise documentReady.

    So scripts at the bottom of the body ALWAYS run before those in the head if they need to interact with the HTML of the page at all. The reason why scripts used to be placed in the head was that it wasn't possible in early browsers to keep the JavaScript separate from the HTML and with JavaScript jumbled with the HTML you could call functions in the head from the HTML before the rest of the HTML finished loading - but only by creating a jumbled mess of HTML and very restrictive and antiquated JavaScript.

    Take a look at the very first example JavaScript in my JavaScript course at http://javascriptexample.net/basics01.php - to move that script tag into the head would require a lot more JavaScript in order to make the message take longer to display. In place of that one statement to run immediately the HTML finishes loading you'd need all of the following JavaScript to load the message AFTER the entire page had loaded - including all the images.

    Code:
    myfunction = function() {
    document.getElementById('ex').innerHTML = 'hello world';
    }
    
    if (window.addEventListener)
    addEvent = function(ob, type, fn ) {
      ob.addEventListener(type, fn, false );
    };
    else if (document.attachEvent)
    addEvent = function(ob, type, fn ) {
      var eProp = type + fn;
      ob['e'+eProp] = fn;
      ob[eProp] = function(){ob['e'+eProp]( window.event );};
      ob.attachEvent( 'on'+type, ob[eProp]);
    };
     
    addEvent(window, 'load', myfunction);
    Not a very friendly introduction to JavaScript compared to my actual example - but the only way to move the script into the head without using antiquated JavaScript embedded into the HTML.
    Last edited by felgall; 06-23-2012 at 01:08 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    basics01.php gives an example of code from a external script that is automatically run. In that case it would be stupid to include the call in a function, and the call the function later on:
    HTML:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <head>
    <title>Example 01</title>
    <script type="text/javascript" src="example01.js"></script>
    </head>
    <body>
    <div id="ex"></div>
    <script>SayHi();</script>
    </body>
    </html>
    Javascript:
    Code:
    function SayHi(){
    document.getElementById('ex').innerHTML = 'hello world';
    }
    Another example could be:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <head>
    <title>Example 01</title>
    <script>
    Urls=['http://www.google.com/','http://www.bing.com/'];
    function GotoUrl(Num){
    location.href=Urls[Num];
    }
    </script></head>
    <body>
    <a href="javscript:void()" onclick="GotoUrl(1)">Go there</a>
    </body>
    </html>
    In this case we are talking about an in-doc function that are triggered by a user action.
    Then I think it would be better to leave the <script> where it is, instead of moving it to right before the </body>

  • #8
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Lerura View Post
    <a href="javscript:void()" onclick="GotoUrl(1)">Go there</a>
    The href attribute needs to be rewritten before 1890. Using JavaScript in the href tag is not necessary after that date unless your intention is for people to right click on the link to download the script into their btrowser.

    The onclick attribute needs to be rewritten before 2006. The death of Netscape 4 means that you should no longer code event handlers jumbled in the HTML and should attach them separately in the JavaScript itself.

    Go to the bottom of the class - that code does not deserve even -10 out of 100 as proper JavaScript for 2006+.

    See http://javascriptexample.net/badjs01.php for an example of where JavaScript should be placed in the href attribute and why it should NEVER be put there for any other purpose.

    See http://javascriptexample.net/badjs03.php for why you shouldn't use onclick in the HTML.

    Any one who writes code such as that statement of yours is desperately in need of taking a class to learn the basics of JavaScript as such commands are only ever used by people who don't know what JavaScript is.
    Last edited by felgall; 06-23-2012 at 03:10 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #9
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    I kinda knew that you would start commenting on the tag itself. And whether it is oldschool or not.
    But I guess that is how you are: Only the most recent way, is the right way.

    But it seems like you don't want to stay on topic ,and focus on what my example is about:
    The placement of an in-doc script triggered by a user action.

    Maybe because you ran out of arguments.... ?!??!?!
    Last edited by Lerura; 06-23-2012 at 04:13 AM.

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Lerura View Post
    And whether it is oldschool/deprecated.
    It is - and for lots of good reasons.

    You should never use deprecated code.

    Deprecated means currently obsolete and flagged for removal from the language - DO NOT USE.

    Most beginner JavaScript problems are caused because they are trying to use outdated deprecated code where the modern replacement way of coding is SPECIFICALLY DESIGNED to make such problems disappear.

    If you want to write your JavaScript for Netscape 2 then you should go back to the 20th Century where you are likely to find visitors who actually use that browser.

    The "rules" for writing modern JavaScript define how JavaScript should be written so as to ensure that it doesn't have problems.

    I have been teaching people how to write JavaScript properly for about eight years now and writing JavaScript properly is far easier than writing and then rewriting that error prone garbage that a lot of people think is JavaScript (but which they keep having to ask for help with every time it causes them problems).
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #11
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    Can you at least try to stay on topic:
    Placement of an in-doc script that is triggered by users action.

    If you try to avoid answering to that, it can only mean that you are unable to answer.

    And your eight years of teaching is obviously a replacement for learning.
    I could improve a lot of you solutions in this forum, but refrained from it, as your solutions sufficed
    Last edited by Lerura; 06-23-2012 at 04:42 AM.

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Lerura View Post
    And your eight years of teaching is obviously a replacement for learning.
    No - I have actually learnt a lot more teaching JavaScript than I did before since the students always come up with unexpected things that you wouldn't come across if you were just coding.


    Quote Originally Posted by Lerura View Post
    I could improve a lot of you solutions in this forum, but refrained from it, as your solutions sufficed
    So could I but I am not prepared to spend the time to totally rework someones code so as to do it properly - I generally just provide enough to fix the specific problem they are having.

    As for your supposedly on topic question about in HTML JavaScript - that's the equivalent of ashing which end of a horse you'd find the motor - the correct answer is that you shouldn't be using in HTML JavaScript at all. For those who still do write such antiquated javaScript the answer of where to place the script for best results is almost the same as for those writing their JavaScript properly.

    All JavaScript works best at the BOTTOM of the page regardless of whether you write it properly or jumble it with the HTML because unless you use an async or defer attribute on the script tag the rendering of the page will be delayed while the script is downloaded and checked for any document.write statements. Since there are still lots of browsers in use that don't support async or defer the only way to prevent the JavaScript slowing the loading of the page is to place it at the very bottom. Any JavaScript intended to interact with the web page will run just as well from the bottom as from in the head even if you don't make any changes to the code to try to get the JavaScript to run faster.

    Placing the script at the bottom will allow the HTML to render faster regardless of how the code is written - with two exceptions.

    1. If the code contains document.write statements then it has to go where the output is to be added to the page (or in a function in the head called from another script at the insertion point - but there's no reason to use document.write any more.
    2. If the script is supposed to decide whether to render the current page or load a new page (eg. a framebreaker script). Such scripts need to go in the head as they need to run before the page renders at all.
    Last edited by felgall; 06-23-2012 at 05:05 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #13
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    Quote Originally Posted by felgall View Post
    As for your supposedly on topic question about in HTML JavaScript - that's the equivalent of ashing which end of a horse you'd find the motor - the correct answer is that you shouldn't be using in HTML JavaScript at all. For those who still do write such antiquated javaScript the answer of where to place the script for best results is almost the same as for those writing their JavaScript properly.
    I didn't ask any question.
    I gave my opinion.

    Using HTML javascript is IMO not wrong if it makes it easier for the coder to keep track of their coding.
    Many question asked here is because less experienced coders are trying to understand coding that are far beyond the experience level.
    You must learn to walk before you can run.

  • #14
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Lerura View Post
    Using HTML javascript is IMO not wrong if it makes it easier for the coder to keep track of their coding.
    But it doesn't - it exposes the script to possible conflicts with other scripts and means that you will spend many times as long to maintain the code than would be required if you made it unobtrusive.

    Just imagine a 10,000 page web site any you have to update every single page because the event handler is hard coded in each page instead of being attached from within the script. Months of repetitive wasted time.

    Just imagine two scripts that both need to run something onload on several thousand pages butr where the rest of the pages only call one or the other. Again months of wasted time updating HTML to fix the JavaScript that shouldn't be there.

    Imagine adding a second script to a page and it stops both scripts from working. Probably only hours to fix but couldn't happen at all if the scripts were written properly.

    Your opinion makes it obvious that you are not a professional programmer or you would have already learnt these lessons.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #15
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    I can easily imagine how much work it requires, if you have to update 10.000 hardcoded pages. And also how much easier it will be if you can make the update by editing a single file instead.

    But there also may sites where the certain script is only relevant for a single page.
    In that case it would be best to have these script in-doc. No need for a separate .js here.
    And the placement is mostly irrelevant here also.

    Such script and calls are best placed where the coder feels that it is easiest to maintain them. especially if you are a low-level coder.
    Personally i make a lot of single-pages, and then i never use use external .js, and therefore the significance of the placement of the script is mostly insignificant.

    But i am also making multipage-sites where most generation is handle by the one script file.

    The importance of the construction/placement/call of the script depends on what you are making.


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