...

View Full Version : Inserting Javascript Code in between the <BODY> tags



jason_kelly
06-22-2012, 08:29 PM
Thread closed, problem solved.

Inserted javascript body text into Head section and called the window.onload()

felgall
06-22-2012, 09:42 PM
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.

Lerura
06-22-2012, 10:21 PM
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.

felgall
06-22-2012, 11:29 PM
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.

Lerura
06-23-2012, 12:26 AM
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.

felgall
06-23-2012, 01:00 AM
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.


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.

Lerura
06-23-2012, 02:43 AM
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:
<!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:

function SayHi(){
document.getElementById('ex').innerHTML = 'hello world';
}
Another example could be:


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

felgall
06-23-2012, 03:05 AM
<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.

Lerura
06-23-2012, 03:27 AM
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.... ?!??!?!

felgall
06-23-2012, 04:16 AM
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).

Lerura
06-23-2012, 04:40 AM
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

felgall
06-23-2012, 05:03 AM
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.



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.

Lerura
06-23-2012, 06:05 AM
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.

felgall
06-23-2012, 07:04 AM
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.

Lerura
06-23-2012, 07:37 AM
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.

Philip M
06-23-2012, 09:04 AM
Your opinion makes it obvious that you are not a professional programmer or you would have already learnt these lessons.

felgall - I think you are getting perilously close to turning into another disagreeable iBall. You ought not to insult Lerura (who is a highly respected member of this forum and a professional coder - as you know very well) in this way, or suggest that people who disagree with you are not professional. You obviously know a very great deal about Javascript but sometimes your lofty and even fanatical-seeming views are highly debateable and open to ligitimate disagreement - from people who may well have had more actual real-life experience of coding than you have.

You often use ridiculous examples such as sites with 10000 pages to make your points - which serves only to undermine your argument.

Do please avoid giving the impression that you are a pompous know-all. Childish insults such as "Go to the bottom of the class - that code does not deserve even -10 out of 100 as proper JavaScript for 2006+" are unworthy of you.

Remeber - iBall is not liked, and because he is not liked he is not respected. Because he is not respected his views do not have the impact that they might otherwise merit. I wouid respectfully but earnestly advise you not to follow the same self-destructive path.

It would be nice if you apologised to Lerura.

felgall
06-23-2012, 11:31 PM
felgall - I think you are getting perilously close to turning into another disagreeable iBall. You ought not to insult Lerura (who is a highly respected member of this forum and a professional coder - as you know very well) in this way, or suggest that people who disagree with you are not professional.


I apologise for anything that I said that might be considered to be a personal attack against anyone. I have an unfortunate tendency to respond in kind when people make such comments about me (as was the case here - although here it was a case of Lerura making a personal attack on me based on assumptions and my responding based on the complete garbage newbie code that Lerura posted so saying that he was not a professional JavaScript programmer is actually far less of a personal attack than the only possible alternative way of describing someone who would use such code would be).

Lerura may be a complete professional when it comes to other languages but has demonstrated only a newbies knowledge of JavaScript in this thread.

Also 10000 pages is NOT a ridiculous example. I personally have had to make exactly the sort of changes I mention to two sites of over 2500 pages each (which once you add in all the pages on smaller sites would total over 10000 pages). That's why I use such examples - they are effectively from my personal experience and the only ridiculous thing about it is that people continue to generate further such problems that will eventually need to be fixed.

Philip M
06-24-2012, 11:04 AM
I apologise for anything that I said that might be considered to be a personal attack against anyone. I have an unfortunate tendency ....

It is indeed a very unfortunate tendency to interpret any kind of criticism or disagreement with your opinions as a personal attack. I think your apology to Lerura is not really adequate and another self-justification - but I suggest we let the issue drop now. But please bear in mind that there are aspects of Javascript where there is scope for legitimate disgreement, or simply more than one equally acceptable alternative way.

Lerura
06-24-2012, 03:19 PM
Lerura may be a complete professional when it comes to other languages but has demonstrated only a newbies knowledge of JavaScript in this thread.

SOOOO WRONG!
I gave an example calling a in-doc function inline, in which case I think the function should be in the head. - Where IMO all in-doc functions should be.
- by giving an example that I believe everyone could easily understand.

But instead of staying on topic: Where the script should be placed in such case, you started attacking my example.
And now you imply that I have insufficient experience, based on how I chose to write my example.

I have 21 years of experience with programming, starting out with a language that most coders, maybe even you, probably never have even heard of: QBasic!
I was able to make things in QBasic, that many coders are still struggling with using javascript.
Even then, it mattered in which of several ways, the tasks where done

In the end Javascript is nothing more than a heavily extended QBasic, with a different syntax.

Don't come here, bragging about your experience.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum