Why use window.onload - javascript

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/

Related

Show page after specific Javascript is loaded

I dont want to reveal html page content if one specific javascript is not fully loaded. I want to show blank page when this javascript is loading. Javascript is located in .js file, so in html page it looks like this:
<script src = "file.js"></script>
Put the script tag into the head element of the html document, e.g.
<!doctype html>
<html>
<head>
<script src="file.js"></script>
</head>
<body>
</body>
</html>
This depends on whether file.js performs asynchronous operations.
If your file contains simple, synchronous code, a hackish solution would be to put document.body.style.display="none" at the start of the code and document.body.style.display="block" at the end. This will hide your document body until the script reaches the end.
A more robust solution would be to make sure all your code is in appropriate functions, and wrap the initial function with a callback that displays the body.
window.onload = runOnLoad( function() { document.body.style.display="block"; } );
function runOnLoad( callback ) {
document.body.style.display="none";
// rest of your code
callback();
}

JavaScript Events - During page is loading or before?

I'm using an event which is called after the complete site is loaded. So I use onload() for that.
Is there any way to call my function before or during the site is loaded?
I would be very grateful!
Thank You!
<html>
<head>
<title>My title</title>
<script>
var x = 2;
function timesTwo(num){
return num * 2;
}
console.log(timesTwo(x));
</script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
That way your JavaScript code is being interpreted and executed before the websites Body is being rendered. Keep in mind, that if you use that approach and are executing some JS that takes up some time, the websites display time will be delayed by same amount.
If you want to call something as early as possible, put it in a script tag at the beginning of the <head> element. However, you can't guarantee any libraries are loaded or any of the page has been loaded yet. If you want to do something as soon as possible, and are using jquery, use $(function() { yourFunctionHere() }). If you aren't using jquery, use the DOMContentLoaded event
You may listen on the 'readystate' event to do something before the 'DOMContent' event. And do not forget to put the snippet in head tag.
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function () {
console.log('DOM content loaded');
};
document.addEventListener('readystatechange', function () {
console.log('[Ready state is]', document.readystate);
if (document.readystate != 'complete') {
console.log('You can do something here');
}
};
</script>
<body>
</body>
</html>
The output can be:
[Ready state is] interactive
You can do something here
DOM content loaded
[Ready state is] complete
Hope it helps.

How to call a JavaScript function when the external JavaScript file is referenced at the end of the HTML body?

I know that when you want to invoke a JavaScript function inside a HTML body section you can do it by putting <script> someFunction(); </script> inside your body tag, here is an example, I have HTML like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
src="/Script.js"></script>
</head>
<body>
<script>
showAlert();
</script>
</body>
</html>
And the javascript file like this:
function showAlert(){
alert("This is an alert!");
}
This works fine but if I put the JavaScript file reference at the end of the body like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<script>
showAlert();
</script>
<script type="text/javascript"
src="/Script.js"></script>
</body>
</html>
the function showAlert() is no longer being invoked. Can you please answer these 2 questions:
Why is showAlert() not invoked in the second scenario?
How (if possible) to invoke a function from a JavaScript file when
it is referenced in the end of the body?
The reason why I'm asking is because I know that it is a good practice to refer your JavaScript files in the end of the body instead of the head, so that the page will be rendered first before loading all the JavaScript code.
1) The scripts are loaded linearly. Since the script has not yet been loaded, the function is undefined. (This is in contrast to function hoisting within a script.)
2) Simply wait till the page loads.
window.onload = function(){
showAlert();
}
(Simply doing window.onload = showAlert won't work because of reason #1. Here you delay evaluation until such time that the function will exist.)
Assuming you want to run showAlert() immediately when the page has loaded, try adding an onload() event handler to call showAlert rather than just calling it as the script loads. This can be done a few ways:
<body onload="showAlert();">
or define the window onload event programatically where your current function all is made in the html
window.onload = new function() {showAlert();}
or (and I think this is the preferred way because it won't cancel out other event handlers bound to the onload event)
window.addEventListener("load", showAlert);
By default, scripts run sequentially. Your code doesn't work because showAlert() runs before loading Script.js, so at that point the function showAlert is not defined yet.
To make it work, you must delay the showAlert call.
The load event has already been mentioned in other answers, but it will wait for all resources (like images) to load. So listening to the DOMContentLoad event is usually better, the function will be called sooner.
<script>
document.addEventListener('DOMContentLoaded', function() {
showAlert();
});
</script>
<script src="data:text/javascript,
function showAlert() {
console.log('Hello!')
}
"></script>
The reason for your script isn't working is the way how a webpage is parsed..From top to bottom..Here is some link (would help to know why script added at bottom).
1) in your First case the browser loaded script when it parsed the page and when you called it in body it was available so it got invoked.
2) in Second scenario (My be typo) You have placed the call to function before loading the script that contain your function. so during page parsing browser wont find it and continue to next line where script containing function is loaded which has no effect for now as it already parsed the call.
If you still want to follow the second scenario you have to trigger the function call (after ensuring all resources being loaded ie Your script).
so you can use window.load=<your function call> or in case of jQuery place it inside
$(document).ready(function(){
//call here
});
Javascript processes in the order given. You are trying to call showAlert before showAlert have been defined. Change to:
<body>
<script type="text/javascript"
src="/Script.js">
</script>
<script>
showAlert();
</script>
</body>
and all should work as intended.

Calling an alert function from a button but without using onclick

What im trying to do, is to call my function from whenever someone clicks on my button. However, i know that it can be done with
<button onclick="myFuntion()>
But i want to skip that step, i dont want a function in my button, i've heard that its bad programming.
However, heres how my file looks.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javacript" src="javascript.js"> </script>
<title> Javascript </title>
<script>
function testFunction(){
document.getElementById("test").onclick = Hello;
}
function Hello(){
alert("Hello");
}
</script>
</head>
<body>
<button type="button" id="test" <!-- I know i can use onclick="testFunction()" here but i dont wanna !-->> Click me </button>
</body>
</html>
So how come it doesnt pop-up with the box "Hello" whenever i push the button, what have I done wrong?
You have to call your testFunction after the HTML body is loaded so that it actually creates he binding.
That is, at the end of the file, you'd do something like:
...
<script>
testFunction()
</script>
</body>
...
If you run that binding code in your head script the button element won't exist yet — that is why this have to be at the end.
JavaScript libraries such as jQuery make this more elegant by providing an ready hook, where one puts code to be called once the page is fully loaded, without having to resort to code on the bottom of the page.
Complete example with script at end (confusingly, Stack Snippets don't show it to you in the order they actually are in the snippet; even though it doesn't look like it, the script is at the end here):
// Scoping function to avoid creating unnecessary globals
(function() {
// The click handler
function Hello() {
alert("Hello");
}
// Hooking it up -- you *can* do it like you did:
//document.getElementById("test").onclick = Hello;
// ...but the modern way is to use addEventListener,
// which allows for more than one handler:
document.getElementById("test").addEventListener(
"click", Hello, false
);
})();
<button type="button" id="test">Click me</button>
window.onload=testFunction;
function testFunction(){
document.getElementById("test").onclick = Hello;
}
function Hello(){
alert("Hello");
}
Just run the line in your testFunction always. As seen here:
https://jsfiddle.net/arugco4b/

External JavaScript does not work with jquery

I wrote a small page with jQuery and an external .js file. But it won't load the jQuery part. Here my Code:
<!DOCTYPE html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/testScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<button id="testBtn">Oh my Goood...</button>
<div id="testDiv">testText</div>
</body>
</html>
And here is my external Script:
alert("no jQuery");
$("button#testBtn").click(function(){
alert("Works!");
});
As you can see, jQuery will load before all other scripts. The alert pops up fine. But if I click the button, nothing happens. If I put the script inside the html document directly, the button event works as expected.
I reviewed these questions: Link and Link. But still not working as expected.
Instead of using the $(document).ready() method, you could also just move your javascript references to the bottom of the page, right above the </body> tag. This is the recommended way to include javascript in webpages because loading javascript blocks the page rendering. In this case it also makes sure the elements are already rendered when the javascript is executed.
You'll need to add the click function inside document ready.
$(document).ready(function(){
$("button#testBtn").click(function(){
alert("Works!");
});
});
Your method fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. Using $(document).ready holds the function execution till the DOM elements are ready.

Categories

Resources