javascript: how to check all code of an html page is loaded - javascript

the program needs invoke a function after all code, including HTML, javascript, CSS, etc., is loaded? Can javascript do it?

for JavaScript
window.onload = function(){
//your code
};
for JQuery
$(document).ready(function(){
//your code
});

window.onload will fire after all images, frames and objects have finished loading on the page. Your question isn't clear enough on whether or not you want the script to wait for those, but if you don't then you need a "document ready" solution.
Firstly, many (all?) DOM-based Javascript frameworks provide this functionality, cross browser in the form of an event. jQuery example:
$(document).ready(function() {
alert("DOM is ready");
});
If you want to do it without the framework, it gets a little more awkward. Most browsers (coughnotIE) provide a DOMContentLoaded event:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', function () {
alert("DOM is ready");
}, false);
}
For IE's part, the defer attribute on a script tag will do the job. You can use conditional comments to make sure only IE parses the script:
<!--[if IE]
<script type="text/javascript" defer>
alert("DOM is ready");
</script>
<![endif]-->

If you're using the jQuery library, you simply do this:
$(document).ready(function() {
// The code you need to have executed after loading the page
});

window.onload = function() {
// Your code here
};
What have you tried?

You can use <body onload="doStuff()">, or you can use window.onload in your script. Check this out.

The jQuery $(document).ready(...) method is triggered when the dom is loaded and can be manipulated and before all scripts, images, etc. are loaded.
The window.onload event will fire when everything that has been requested has completed loading.

Related

addEventListener is Not Working as Expected (Inner HTML is not Populating) [duplicate]

I need to execute some JavaScript code when the page has fully loaded. This includes things like images.
I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.
That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.
window.addEventListener('load', function () {
alert("It's loaded!")
})
For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.
Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDN documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.
Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:
<script>history.navigationMode = 'compatible';</script>
If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:
<img src="javascript:location.href='javascript:yourFunction();';">
For example, I use this trick to preload a very large file into the cache on a loading screen:
<img src="bigfile"
onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();">
Try this it Only Run After Entire Page Has Loaded
By Javascript
window.onload = function(){
// code goes here
};
By Jquery
$(window).bind("load", function() {
// code goes here
});
Try this code
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details
Javascript using the onLoad() event, will wait for the page to be loaded before executing.
<body onload="somecode();" >
If you're using the jQuery framework's document ready function the code will load as soon as the DOM is loaded and before the page contents are loaded:
$(document).ready(function() {
// jQuery code goes here
});
the window.onload event will fire when everything is loaded, including images etc.
You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.
You may want to use window.onload, as the docs indicate that it's not fired until both the DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.
In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:
<script type="module">
alert("runs after") // Whole page loads before this line execute
</script>
<script>
alert("runs before")
</script>
also older browsers will understand nomodule attribute. Something like this:
<script nomodule>
alert("tuns after")
</script>
For more information you can visit javascript.info.
And here's a way to do it with PrototypeJS:
Event.observe(window, 'load', function(event) {
// Do stuff
});
The onload property of the GlobalEventHandlers mixin is an event
handler for the load event of a Window, XMLHttpRequest, element,
etc., which fires when the resource has loaded.
So basically javascript already has onload method on window which get executed which page fully loaded including images...
You can do something:
var spinner = true;
window.onload = function() {
//whatever you like to do now, for example hide the spinner in this case
spinner = false;
};
Completing the answers from #Matchu and #abSiddique.
This:
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
Is the same as this but using the onload event handler property:
window.onload = (event) => {
console.log('page is fully loaded');
};
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Live example here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#live_example
If you need to use many onload use $(window).load instead (jQuery):
$(window).load(function() {
//code
});
2019 update: This is was the answer that worked for me. As I needed multiple ajax requests to fire and return data first to count the list items.
$(document).ajaxComplete(function(){
alert("Everything is ready now!");
});

Event listener after all resources loaded and all scripts executed [duplicate]

I need to execute some JavaScript code when the page has fully loaded. This includes things like images.
I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.
That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.
window.addEventListener('load', function () {
alert("It's loaded!")
})
For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.
Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDN documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.
Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:
<script>history.navigationMode = 'compatible';</script>
If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:
<img src="javascript:location.href='javascript:yourFunction();';">
For example, I use this trick to preload a very large file into the cache on a loading screen:
<img src="bigfile"
onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();">
Try this it Only Run After Entire Page Has Loaded
By Javascript
window.onload = function(){
// code goes here
};
By Jquery
$(window).bind("load", function() {
// code goes here
});
Try this code
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details
Javascript using the onLoad() event, will wait for the page to be loaded before executing.
<body onload="somecode();" >
If you're using the jQuery framework's document ready function the code will load as soon as the DOM is loaded and before the page contents are loaded:
$(document).ready(function() {
// jQuery code goes here
});
the window.onload event will fire when everything is loaded, including images etc.
You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.
You may want to use window.onload, as the docs indicate that it's not fired until both the DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.
In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:
<script type="module">
alert("runs after") // Whole page loads before this line execute
</script>
<script>
alert("runs before")
</script>
also older browsers will understand nomodule attribute. Something like this:
<script nomodule>
alert("tuns after")
</script>
For more information you can visit javascript.info.
And here's a way to do it with PrototypeJS:
Event.observe(window, 'load', function(event) {
// Do stuff
});
The onload property of the GlobalEventHandlers mixin is an event
handler for the load event of a Window, XMLHttpRequest, element,
etc., which fires when the resource has loaded.
So basically javascript already has onload method on window which get executed which page fully loaded including images...
You can do something:
var spinner = true;
window.onload = function() {
//whatever you like to do now, for example hide the spinner in this case
spinner = false;
};
Completing the answers from #Matchu and #abSiddique.
This:
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
Is the same as this but using the onload event handler property:
window.onload = (event) => {
console.log('page is fully loaded');
};
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Live example here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#live_example
If you need to use many onload use $(window).load instead (jQuery):
$(window).load(function() {
//code
});
2019 update: This is was the answer that worked for me. As I needed multiple ajax requests to fire and return data first to count the list items.
$(document).ajaxComplete(function(){
alert("Everything is ready now!");
});

How do I run a jQuery function after jQuery is loaded?

At my website, I am loading jQuery asynchronously.
In order to do that, I must run jQuery functions only after it is really loaded.
I've tried two pure JS ways:
<script src="js/jquery-2.2.2.min.js" async></script>
<script>
window.addEventListener('load', function() {
//stuff
}, true);
</script>
And
window.onload = function() {
//stuff
}
But even so I still get Uncaught TypeError: $(...) is not a function at...
How do I fire jQuery functions after the lib is fully loaded?
You need to add the script only after jQuery library is loaded using script tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// your code should be here
alert(typeof jQuery)
</script>
The document ready handler is using to execute the code only after DOM elements are loaded.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
console.log('Outside document ready handler ' + $('.test').length)
$(document).ready(function() {
console.log('Inside document ready handler ' + $('.test').length)
});
</script>
<div class="test"></div>
UPDATE 1: You can use defer if script is in a file, refer following question: jquery loaded async and ready function not working
UPDATE 2: Or you can bind load event handler to the script tag using addEventListener method.
<script async id="script" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('script')
.addEventListener('load', function() {
alert(typeof jQuery)
});
</script>
FYI : I don't know why you are doing this, for optimizing the speed of content load it's always better to move the script tags at the end of body which helps to load content first.
You could do something like this:
function checkVariable(){
if ( window.jQuery){
Do your jquery stuff here
}
else{
window.setTimeout("checkVariable();",100);
}
}
checkVariable();
Apologies for the formatting...stuck on my phone right now.
I did not see this method listed, so I thought I would demonstrate using the JavaScript HTML DOM EventListener.
Example #1 Using the jQuery.ready() Method:
<p id="test-jquery">jQuery Not Loaded</p>
<script>
$(document).ready(function() {
var elem = $('#test-jquery');
elem.text('jQuery Is Loaded');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method will not work since jQuery has yet to be loaded.
Running the above example will output:
ERROR: {
"message": "ReferenceError: $ is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 13,
"colno": 3
}
Example #2 Using the addEventListener() Method:
<p id="test-jquery">jQuery Not Loaded</p>
<script>
window.addEventListener('DOMContentLoaded', function() {
var elem = $('#test-jquery');
elem.text('jQuery Is Loaded');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method will work since we are listening for the Window DOMContentLoaded event.
From Mozilla:
The original target for this event is the Document that has loaded.
You can listen for this event on the Window interface to handle it in
the capture or bubbling phases. For full details on this event please
see the page on the Document: DOMContentLoaded event.
A different event, load, should be used only to detect a fully-loaded
page. It is a common mistake to use load where DOMContentLoaded would
be more appropriate.
You can use this:
<script>
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
// window loaded, external resources are loaded too...
jQuery(function($) {
// your code here: $("a").css(...)
}
}
});
</script>
I used it when inline jQuery script did not work on safari (Mac and iOS) and this solved the problem.
Use document.ready or load the library in the header. That should work.. Be sure to load in the right folder or in the right link. If you are usying a link to load jquery then be sure to have an internet connection

Is browser fully loaded check

Is there anyway to check if page is fully loaded.Something like this http://msdn.microsoft.com/en-us/library/system.web.ui.page.loadcomplete.aspx but for JAVA.
If you intend to execute logic on the client side when the page is loaded, you might be interested in the Javascript onload event.
Or, even better, consider using jQuery and use the ready() function to execute your logic.
Just a short example using jQuery:
$(document).ready(function() {
alert("The document, including all assets such as images, has been completely received");
});
Not directly in java, since it is probably not running in the browser, but you can do it with javascript
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">var myFunc = function() {
alert("The page is fully loaded!");
};
window.onload = myFunc;
</script>
</head>
you can use the normal onload()
<body onload="yourFunctionHere()">
or the JQuery version
$(document).ready(function() {
yourFunctionHere();
});
1. JQuery will help you:
there is $(document).ready() which tell you that the browser is loaded.
Example:
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
The ready event occurs when the DOM (document object model) has been loaded, and the page has been fully loaded (including images).
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
2.Window onload is another JavaScript approach:
window.onload=function(){SomeJavaScriptCode};
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
Note: The main difference is that document.ready() event gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully, while window.onload will wait until all your contents are loaded fully.
We can have more than one document.ready() function in a page where we can have only one onload function.
Not in Java, no.
You'll need Javascript:
<script>
window.onload = function() {
alert('Loading Complete!');
}
</script>

$(document).ready() fires too early

So, I need to know the width of an element with javascript, the problem I have is that the function fires too early and the width changes when the css is tottally applied. As I understood, the $(document).ready() function was fired when the document is completed, but it doesn't seem to work like that.
Anyways, I'm sure that with the code my problem will be understood (this is a simplified example):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Parisienne' rel='stylesheet' type='text/css'>
<style type="text/css">
#target {
font-family: 'Parisienne', cursive;
float: left;
}
</style>
</head>
<body>
<div id="target">Element</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
console.debug($('#target').outerWidth());
alert('hold on');
console.debug($('#target').outerWidth());
});
</script>
I want to know the width of the #target div, the problem is that the code that's executed before the alert gives a different output than the one after, presumably because the font is not fully loaded and it's measuring the div with the default font.
It works as I expect in Google Chrome, but it doesn't on IE and Firefox.
If you rely on external content to be already loaded (e.g. images, fonts), you need to use the window.load event
$(window).on("load", function() {
// code here
});
The behaviour of these events is described in this article:
There is [a] ready-state however known as DOM-ready. This is when the browser has actually constructed the page but still may need to grab a few images or flash files.
Edit: changed syntax to also work with jQuery 3.0, as noted by Alex H
Quote OP:
"As I understood, the $(document).ready() function was fired when the document is completed,"
$(document).ready() fires when the DOM ("document object model") is fully loaded and ready to be manipulated. The DOM is not the same as the "document".
W3C - DOM Frequently Asked Questions
You can try $(window).load() function instead...
$(window).load(function() {
// your code
});
It will wait for all the page's assets (like images and fonts, etc.) to fully load before firing.
The jQuery .ready() function fires as soon as the DOM is complete. That doesn't mean that all assets (like images, CSS etc) have been loaded at that moment and hence the size of elements are subject to change.
Use $(window).load() if you need the size of an element.
The "ready" event fires when the DOM is loaded which means when it is possible to safely work with the markup.
To wait for all assets to be loaded (css, images, external javascript...), you'd rather use the load event.
$(window).load(function() {
...
});
You could use $(window).load(), but that will wait for all resources (eg, images, etc). If you only want to wait for the font to be loaded, you could try something like this:
<script type="text/javascript">
var isFontLoaded = false;
var isDocumentReady = false;
$("link[href*=fonts.googleapis.com]").load(function () {
isFontLoaded = true;
if (isDocumentReady) {
init();
}
});
$(document).ready(function () {
isDocumentReady = true;
if (isFontLoaded) {
init();
}
});
function init () {
// do something with $('#target').outerWidth()
}
</script>
Disclaimer: I'm not totally sure this will work. The <link> onload event may fire as soon as the stylesheet is parsed, but before its external resources have been downloaded. Maybe you could add a hidden <img src="fontFile.eot" /> and put your onload handler on the image instead.
I have absolutely, repeatably seen the same problem in IE9 and IE10. The jquery ready() call fires and one of my <div>'s does not exist. If I detect that and then call again after a brief timeout() it works fine.
My solution, just to be safe, was two-fold:
Append a <script>window.fullyLoaded = true;</script> at the end of the document then check for that variable in the ready() callback, AND
Check if $('#lastElementInTheDocument').length > 0
Yes, I recognize that these are nasty hacks. However, when ready() isn't working as expected some kind of work-around is needed!
As an aside, the "correct" solution probably involves setting $.holdReady in the header, and clearing it at the end of the document. But of course, the really-correct solution is for ready() to work.
The problem $(document).ready() fires too early can happen sometimes because you've declared the jQuery onReady function improperly.
If having problems, make sure your function is declared exactly like so:
$(document).ready(function()
{
// put your code here for what you want to do when the page loads.
});
For example, if you've forgotten the anonymous function part, the code will still run, but it will run "out of order".
console.log('1');
$(document).ready()
{
console.log('3');
}
console.log('2');
this will output
1
3
2

Categories

Resources