Window is loading first than DOM with jQuery on Google Chrome - javascript

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.

Related

JavaScript - Loading the entire webpage not specific div

I'm new to JavaScript and I'm sure that this is a very trivial fix.
I'm dynamically changing a div content based on which button is clicked. This example works in JSFiddle but however when I put it on my PC it simply loads the entire webpage even when I wrap the JS with $(window).load(function(){ ... })
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul class="menu">
<li>About</li>
<li>Contact</li>
<li>Misc</li>
</ul>
<div id="about" class="menu-content">About</div>
<div id="contact" class="menu-content">Contact</div>
<div id="misc" class="menu-content">Misc</div>
</body>
</html>
My JS (script.js):
$(window).load(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
$(window).load(function(){ ... })
replace by :
$(document).ready(function(){ ... })
Replace your (window).load to (document).ready
load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.
load()
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 and sub-frames have finished
loading.
ready()
While JavaScript provides the load
event for executing code when a page
is rendered, this event does not get
triggered until all assets such as
images have been completely received.
In most cases, the script can be run
as soon as the DOM hierarchy has been
fully constructed. The handler passed
to .ready() is guaranteed to be
executed after the DOM is ready, so
this is usually the best place to
attach all other event handlers and
run other jQuery code. When using
scripts that rely on the value of CSS
style properties, it's important to
reference external stylesheets or
embed style elements before
referencing the scripts.
try this
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
You can try below solution :
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
When i ran your snippet in my PC, I found out that Jquery was not able to find div, based on the selectors you have specified at the time of loading.

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

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.

Appending text/elements to a DIV tag

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

Categories

Resources