document.onload() strange behaviour, few questions? - javascript

Before you start reading, don't vote me down, its not just another question about window.onload vs document.onload.
window.onload should trigger once all DOM nodes are fully loaded.
document.onload should trigger once all DOM nodes are ready, it won't wait for all the assets to fully load.
Now if we have something like this with window.onload:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
window.onload = function() {
alert('Loaded!');
};
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
The script will wait until image is fully loaded and then trigger alert.
And if we have something like this with document.onload:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
document.onload = function() {
alert('Loaded!');
};
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
Nothing will happen and script won't load at all, unless we make our function self executing like this:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
document.onload = function() {
alert('Loaded!');
}();
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
And now the script will work but won't wait for image to fully load like it does with window.onload.
Now I have 2 questions really:
Why do we need to create self executing functions with document.onload, and window.onload works without making our function self executing? It works the same in latest versions of Chrome and Firefox so I guess its how it its suppose to work, but why?
What is really happening there with that code once we assign document.onload a function? I understand that its a way to wait for DOM to load. But we are saying that window.onload = function() { } Should this make a window a function? Or is that window has eventListener attach to it, that is triggered by onload trigger? Looks like answered this question myself... :) Is it true?
Thanks!

document.onload should trigger once all DOM nodes are ready, it won't wait for all the assets to fully load.
You are operating under a misapprehension. That is not the case.
Why do we need to create self executing functions with document.onload
Because there is no such thing as document.onload. It is an arbitrary property name with no special meaning.
If you assign a function to it, nothing will happen other than that its value will be the function.
If you immediately invoke the function and assign the return value, then the function will be invoked (immediately, before the DOM is ready) and nothing special will happen to the value you store on the property.
If you want to run a function when the DOM is ready then use the DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});

Related

what's the difference between onload action and an action in a bottom script

Is there any functional difference between using body onload:
<!DOCTYPE html>
<html>
<head>
<title>testing body onload</title>
</head>
<body onload="fu('this is from body onload')">
<h2 id="I1">nothing yet</h2>
<script>
function fu (msg) {
document.getElementById("I1").innerHTML = msg ;
}
</script>
</body>
</html>
on the one hand and executing a script at the end of the body:
<!DOCTYPE html>
<html>
<head>
<title>testing body onload</title>
</head>
<body>
<h2 id="I1">nothing yet</h2>
<script>
function fu (msg){
document.getElementById("I1").innerHTML = msg ;
}
fu('this is from bottom script') ;
</script>
</body>
</html>
The second seems better to me, certainly when there are more actions to do when a page is loaded. But maybe there is a pitfall I don't know?
Yes, there is. Putting your code at the bottom is like putting it in a domready event, not onload.
Domready means that the html code was read (so the dom is ready, or in other words, you can now find dom elements with js selectors), while onload means that all the assets (img, css, etc..) are loaded as well (so, a much longer event).
Edit:
please also refer to MDN docs:
(this is basically like jquery's domready, and it's a document object's event):
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
this is the onload event, and it's a window object's event:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
onload documentation from Mozilla:
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images, scripts, links and sub-frames have finished loading.
Placing scripts at the base of the page will run as soon as the browser has rendered the HTML.
For perception purposes I would combine the two and place your scripts at the bottom of the page in an onload callback, if needed.

Attaching onclick event to element is not working

I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?
the following is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading.
To make your code work, you can try following solutions:
Place your script tag below in the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
Add an event handler to check if the window element is ready:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
Another solution would be to use jquery framework and the related document ready function
http://api.jquery.com/ready/
I think the solve you are looking for is
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).
$(function() {
//your javascript code here
});
Why using self executing function?

javascript code not work in HEAD tag

My webpage has the following code:
<html>
<head>
<title>This is test Page</title>
<script language="javascript" type="text/javascript">
document.getElementById("msg1").innerHTML = document.URL.toString();
</script>
</head>
<body>
<div class="sss">
<p id="msg1"></p>
</div>
</body>
</html>
As you now at the time the script executes the div doesn't exist but I want to put my JavaScript code only In the <head> tag and I won't put it in middle of HTML code.
But this code only works when I put the <script> tag after the <div> tag.
I use VS2010 and firefox 19.0.1
Is there anyway to put code in <head> tag?
Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.
<script language="javascript" type="text/javascript">
window.onload = function() {
document.getElementById("msg1").innerHTML = document.URL.toString();
}
</script>
The various tags in your HTML page are loaded and processed in the order in which they appear on the page. Your <script> tag is executed immediately when it is parsed in the <head>. This is before the <body> and the elements inside the <body> are parsed. So, the script tries to reference an element that is not defined at the time it is executed.
Michael Geary is right, in order to execute your code, I'd use jQuery library (a de-facto standard in JS development) and utilize the DOM ready event. This will ensure the code in the handler will execute once DOM is fully loaded.
<script>
$(function(){
$('#msg1').html(document.URL.toString());
});
</script>
I recommend to to use addEventListener like this:
<script language="javascript" type="text/javascript">
document.addEventListener("DOMContentLoaded",() => {
document.getElementById("msg1").innerHTML = document.URL.toString();
});
</script>
Your script uses dom element and must run after the dom loaded.
Wrap your code in a function and call it after dom loaded
function myfunc(){
//code here
}
window.onload = myfunc();

How to call a JavaScript function, declared in <head>, in the body when I want to call it

I have a working JavaScript function declared in the head of an HTML page. I know how to create a button and call the function when the user clicks the button. I want to call it myself some where on the page:
myfunction();
How do I do it?
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
Just drop
<script>
myfunction();
</script>
in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.
You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script> This way the code will get executes on Page Load.

Basic jQuery .load Problem

I am trying to use jQuery's .load function to dynamically load content into my webpage. This seem so simple, but I cannot make it work. To try and figure it out, I made a test page with just basic structure, but the external content still won't load:
jquery.html
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$('#foo').load('test.html');
</script>
<div id="foo"></div>
</body>
</html>
test.html
<p>Text text</p>
I'm sure I have made a tiny error, but I can't find it anywhere!
You need to encapsulate your script in the $(document).ready() otherwise #foo won't exist when the script is executed:
<script>
$(document).ready(function(){
$('#foo').load('test.html');
});
</script>
You need to wait for the document to be ready before you can access the DOM. Just add a $(document).ready() around your original code:
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$(document).ready( function() {
$('#foo').load('test.html');
});
</script>
<div id="foo"></div>
</body>
</html>
or if you want a shorter code:
$(function() {
$('#foo').load('test.html');
});
Informally, what's happening is that, as your browser reads the code you wrote, it's drawing its contents as it goes along. When it reaches your <script> tag, it executes it. But when $("#foo") gets executed, the browser's still processing the <script> and hasn't reached the part of the code where you told it there's a div called foo, so the browser doesn't know it exists, and jquery will just find nothing.
Of course, the idea that the browser will just sequentially read your code and render it as it goes is naive at best, so while it might seem that just moving the <script> tag to the bottom of the code would work, you're not actually guaranteed it will work. Instead, the browser will notify you when it's done drawing the page by firing a load (and possibly a DOMContentLoaded) event. So all code that depends on the whole html being drawn should be executed in an event handler bound to those events.
jQuery makes waiting for the page to be loaded easy, just use something like this:
$.ready(function() {
doStuff();
});

Categories