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 ...
Related
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.
I'm new to jQuery.I have learned that DOM content will be loaded first and then window.onload event will occur as all the style sheets and images have to be loaded.
But this doesn't turn out for me with the following code
<!DOCTYPE html>
<html>
<head>
<title>Add Event Listener</title>
<script type="text/javascript" src="../jquery-3.2.1.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
alert("DOM Loaded");
});
$(window).on("load",function(){
alert("Window Loaded");
});</script>
</head>
<body>
</body>
</html>
After Opening this on Google Chrome (63.0.3239.108) I'm getting an alert that Window is Loaded prior to the alert of "DOM Loaded".
Same problem with Microsoft Edge (40.15063.0.0)
But,this works fine with Firefox(57.0.3)
Can anyone explain this?
Thanks in advance !
This Question is not a duplicate of
window.onload seems to trigger before the DOM is loaded (JavaScript)
That is because you test it without any image to load...
So all the markup has been parsed and all loaded. So the load event occurs.
Then when the script has been parsed, the ready occurs.
It usually is the script that is parsed faster, when there is images to load.
See below what happens when there is one.
$(document).ready(function(){
alert("DOM Loaded");
});
$(window).on("load",function(){
alert("Window Loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://static.pexels.com/photos/132037/pexels-photo-132037.jpeg">
They are events and are triggered by a state being achieved. They are not interdependent events, so they have no fixed order.
window.onload fires once all resources declared in the html document are downloaded.
document.onload fires once the dom is built.
They are not dependent on each other. The dom can be built prior to the last resource being downloaded. All of the resources could download prior to the dom being built.
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/
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 :)
How do I add text/elements to a target element (div) using getElementById (without jquery) when the page loads?
Here's my markup currently:
<html>
<head>
<title>test</title>
<script language="javascript">
/document.getElementById('content').innerHTML = 'Fred Flinstone';
</script>
</head>
<body>
<div id="content">
dssdfs
</div>
</body>
</html>
<script type="text/javascript">
function dothis()
{
document.getElementByID('content').innerHTML = 'Fred Flinstone';
}
</script>
<body onLoad="dothis()">
...
</body>
I think what is happening is that your script is executing before your document is ready. Try placing your javascript in a body load event.
The quickest (although not the best) way to do it is to put your script block towards the end of the HTML file (after the <div> you wish to modify).
The better way to do it is to register for DOM load notification
If you want it to execute after the page loads, then you need to observe the DOM loaded event. You can do that by subscribing to the DOM load event in the script block and then put the code that manipulates the DIV in the event handler.
The tricky part is that different browsers may need slightly different ways to register to be notified when the DOM is loaded (that's were jQuery or a different library becomes useful)
Here's some more information about different ways to register for a callback to be called when the DOM is loaded. The information may be a bit out of date as more modern versions of the popular browsers have become more standards compliant now: http://www.javascriptkit.com/dhtmltutors/domready.shtml