Difference between onload and script at end of body? - javascript

I'm new to JS and I'm not sure when exactly the functions are executed.
Example A:
<html>
<head>
<title>A</title>
<script src="myScript.js"></script>
</head>
<body onload="myFunction()">
[Content here...]
</body>
</html>
Example B:
<html>
<head>
<title>B</title>
<script src="myScript.js"></script>
</head>
<body>
[Content here...]
<script>
myFunction();
</script>
</body>
</html>
From what I've read so far the function is executed when the parser reaches it. Wouldn't that make example A and B the same? Is all the content (e.g. a table with text) of the page visible on the screen when myFunction() is called in B?

Adding the <script> at the end of the body essentially runs it once the items before that <script> are processed (you can think of it like running when the DOM of the body is done). Although onload waits not only for the DOM, but for all the contents inside to be completely done loading, such as images.

onLoad will wait untill the whole document has finished loading with images and such. The good thing about putting your scripts before the closing body tag, is that the user would see the page rendered sooner, if you have a heavy script in your head that takes a couple of seconds to download, the user would see a blank page until it loads the scripts and continues downloading the rest of the document. I would use both, onLoad to make sure the scripts gets executed when everything has loaded, and scripts at bottom so that users has the feeling that the page is loading fast :)

Related

InnerHTML not working on external Java Script file

Javascript external file code:
document.getElementById("not-working").innerHTML=person.firstname+person.nickname+person.lastname+"is"+"awesome.";
I am trying to write the innerHTML in my HTML document by writing the above in my external Java Script file but it's not working.
My HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="home.js"></script>
<p id="demo">
Hello, this is Maqnoon.
<button onclick="myFunction()">Click me</button>
</p>
<p id="hello"></p>
<p id="not-working"></p>
</body>
</html>
Put your external JS importing <script> tag right after the ending </body> tag. Also, put your JS codes inside of the DOMContentLoaded listener like this,
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
function myFunction() {
// ...
}
});
Edit:
Explanation: The browser interprets the HTML from top to bottom, line by line. When you put the JS in the header section of the HTML, there is a possibility that your JS will finish running before the browser reaches to the elements in the later sections of your HTML. In that case, the JS will not be able to see the elements that are going to be loaded right after, maybe a few milliseconds or nanoseconds later. This is why it is advisable to put the <script> tags after your </body> element so that by the time the browser reaches to the JS, the HTML elements are already loaded.
To take it a step further, there is the 'DOMContentLoaded' event which is fired by the browser when it finishes loading the HTML. So, we put our JS code in it to make sure that the code runs after the entire HTML is loaded and available.

Script tags - not linking (JS platform game)

I'm working through the 'create a platform game' project from Eloquent JavaScript and have an issue with script tags.
In the book we're told to display our level using:
<link rel="stylesheet" href="css/game.css">
<script>
var simpleLevel = new Level(simpleLevelPlan);
var display = new DOMDisplay(document.body, simpleLevel);
</script>
I've tried adding this (together with an additional script tag for my platform.js file) into index.html but the browser is giving nothing back, not sure what I'm doing wrong?
Ensure you are inserting your scripts in the right order:
<!DOCTYPE html>
<html>
<head>
Here you should put your "included" scripts with <script src=...>
</head>
<body>
...
</body>
<script>
Here you should put your first execution, if it needs the html page been completely loaded (as to use document.body).
</script>
</html>
The scripts are being executed as they appear into the page. If you use document, you have to delay the execution until the whole page has been loaded: Either by putting your script at the end of the HTML, either by putting an initialization function within the HEAD, and call it from body onload:
<head>
<script>
function myFunction(){...}
</script>
</head>
<body onload="return myFunction()">
...
</body>
Make sure to include the external JavaScript file you need in a separate <script> tag before your inline script!

Why use window.onload

I have tried finding an answer to this on my own, but only found instructions on how to use onload events. I seem to be missing the point.
I've been taught that if I want something to happen when the page loads, I should use window.onload like this:
<script>
window.onload = dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
But now that I am thinking on my own I wonder what the point of doing that is. Because this also produces the same result:
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
Anything I put at the top inside <script> is going to execute anyway... so what's the point of window.onload?
If you're directly running your code with dosomething();, you're delaying your browser's rendering for the time it takes your JavaScript code to run.
You can try to insert your code to the <head> of your html document:
<!DOCTYPE html>
<html>
<head>
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body>
Does not render before the alert is dismissed!
</body>
</html>
You'll see that the page stays blank until you dismiss the alert. So every second the browser takes to run your JavaScript code is a second that your users have to wait for the site to be rendered.
Now if you change the code to be run on body's onload, the page gets rendered before the alert is shown:
<!doctype html>
<html>
<head>
<script>
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body onload="dosomething()">
This page gets rendered before the alert!
</body>
</html>
Consider these two blocks of code:
<head>
<script>
alert(document.getElementById('foo').value);
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
<head>
<script>
window.onload = function() {
alert(document.getElementById('foo').value);
}
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
In the first example, we'll get an error because the element you are referencing isn't found when the script runs - and so you are trying to get value of null.
In the second example, document.getElementById() will find the element with the id foo, because window.onload will get fired only when the complete DOM has been loaded and so the element is available.
window.onload will fire once the DOM has finished loading. In your example, the DOM is not required. However, the following code will fail if the DOM has not yet loaded:
function doSomething() {
alert(document.getElementById('test').innerText);
}
// Throws: TypeError: Cannot read property 'innerText' of null
Assuming your page contains an element with id test, it will alert its text.
waiting for the onload event assures you that all of your scripts and resources are loaded
Assume you are using jquery in your page and you invoked a function that uses it directly without onload , you can't guarantee that the jquery file has been loaded, which will lead to errors and possibly ruining your whole logic
The onload event is handy to make sure the page is fully loaded before you run a script. For your example above it doesn't make sense, but if your page is still loading an item on the bottom and you try to call it then nothing will run.
I recommend using jQuery and using the ready function. This way you will ensure your page is completely loaded.
$( document ).ready(function() {
// This will only run after the whole page is loaded.
});
If you don't want to load query, just put your javascript at the bottom of the page. It's best practice, and ensures the DOM is loaded in full.
For more info on the jquery ready function go here: https://api.jquery.com/ready/

Window.onload vs procedural execution

When using procedural style the code seemed to be executing with the wrong width dimensions of an element (i suspect the code was executing before the element was finished being created), when i refreshed the page all was fine.
Issue:
<html>
<head></head>
<body>
<div id="parent">
</div>
<script language="javascript" type="text/javascript">
create_object(); // Creates an element and puts it inside div parent
</script>
</body>
</html>
Solution:
<html>
<head>
<script language="javascript" type="text/javascript">
window.onload = function(){
create_object(); // Creates an element and puts it inside div parent
}
</script>
</head>
<body>
<div id="parent">
</div>
</body>
</html>
What is the difference?
The window.onload waits for the page to load of course but since the is after the element.. shouldn't that be just fine?
No other java script is being executed on the page.
window.onload waits for all page resources (such as images and style sheets) to be loaded before calling its callback. In your first example, the DOM elements will all exist (because your code is executing at the end of the body after things before it have been parsed), but external resources like images may not yet be loaded and thus final layout may not yet be achieved so everything may not yet have its final size/layout.
window.onload is executed when DOM tree is ready and all resources are loaded (image, script, stylesheet ...). If you load your script in body without this callback, your div width can be wrong if you load image or stylesheet into this bloc ...

Is it possible to define a function in <body> tag of <html> and call it form the <script> tag

I am new to HTML and Javascript, and I have a strange doubt
Is it possible to define a function in "body" tag of html and call it form the "script" tag
Till now i am trying this...
<!DOCTYPE html>
<html>
<head>
<script>
myFunction()
</script>
</head>
<body>
function myFunction()
{
alert("Hello World!");
}
</body>
</html>
No not possible. Browser only understands javascript within the <script> tag.
It will not work, try this,
<html>
<body>
<script>// don't miss script tags for javscript code
function myFunction()
{
alert("Hello World!");
}
</script>
<script>
myFunction(); // call if you have defined function earlier
</script>
</body>
</html>
IMHO:
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
myFunction();
</script>
</head>
<body>
</body>
</html>
or you can use body Onload.
No U cant do it.....U should put js function within the script tag.....
you can do like this
<!DOCTYPE html>
<html>
<head>
<script>
myFunction();
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
<script>
function myFunction()
{
alert("Hello World!");
}
myFunction()
</script>
</body>
</html>
I agree with Rohan but just to check I removed the 2nd pair of script tags and called the function in the same script block as it was defined and it worked but this is not normally the way things are done and this is not normally the use of an embedded JavaScript (js)
Doing a little extra research to find the best/optimum place for embedded js appears to be at the bottom of a webpage before the /body (closing body) tag
Here's a link to Yahoo's "speed up your website" guide:
Yahoo! Developer Network: Best Practices for Speeding Up Your Web Site
and here's the text from the page that refers to embedded js:
Put Scripts at the Bottom
tag: javascript
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
Also, if you go to the site and click the JavaScript tag you get a whole list of optimisations and tips - refer to the image!

Categories

Resources