Execute javascript on whole dom is loaded [duplicate] - javascript

I'm working without the JavaScript framework, but I want to call a function just when the DOM is loaded.
I can't/don't want to use the attribute onload on the <body> tag.

I think http://code.google.com/p/domready/ is exactly what you're looking for.
If you are ever writing your own JavaScript file that cannot depend on
the existing libraries out there and would like to execute only after
the page is loaded, this library is for you.
Simply do this:
<html lang="en">
<head>
<script src="domready.js" type="application/javascript"></script>
<script type="application/javascript">
DomReady.ready(function() {
alert('dom is ready');
});
</script>
</head>
<body>
</body>
</html>

Here is the code:
in non-IE browsers, use DOMContentLoaded event
in IE top frame use scroll hack (see _readyIEtop)
in IE frame, simply use onload
var onready = function(handler) {
// window is loaded already - just run the handler
if(document && document.readyState==="complete") return handler();
// non-IE: DOMContentLoaded event
if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
// IE top frame: use scroll hack
else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
// IE frame: use onload
else if(window.attachEvent) window.attachEvent("onload",handler);
};
// IE stuff
var _readyQueue = [];
var _readyIEtop = function() {
try {
document.documentElement.doScroll("left");
var fn; while((fn=_readyQueue.shift())!=undefined) fn();
}
catch(err) { setTimeout(_readyIEtop,50); }
};
jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.
var test = function() { alert("ok"); }
onready(test);

Well, I'm afraid cross-browser and DOM loaded don't go together easily. By recommendation is Ryan Morr's ondomready (https://github.com/ryanmorr/ondomready) but there are a ton of alterntives.

Related

Show success alert message after page reload [duplicate]

I'm executing an external script, using a <script> inside <head>.
Now since the script executes before the page has loaded, I can't access the <body>, among other things. I'd like to execute some JavaScript after the document has been "loaded" (HTML fully downloaded and in-RAM). Are there any events that I can hook onto when my script executes, that will get triggered on page load?
These solutions will work:
As mentioned in comments use defer:
<script src="deferMe.js" defer></script>
or
<body onload="script();">
or
document.onload = function ...
or even
window.onload = function ...
Note that the last option is a better way to go since it is unobstrusive and is considered more standard.
Triggering scripts in the right moment
A quick overview on how to load / run the script at the moment in which they intend to be loaded / executed.
Using "defer"
<script src="script.js" defer></script>
Using defer will trigger after domInteractive (document.readyState = "interactive") and just before "DOMContentLoaded" Event is triggered. If you need to execute the script after all resources (images, scripts) are loaded use "load" event or target one of the document.readyState states. Read further down for more information about those events / states, as well as async and defer attributes corresponding to script fetching and execution timing.
This Boolean attribute is set to indicate to a browser that the script
is meant to be executed after the document has been parsed, but before
firing DOMContentLoaded.
Scripts with the defer attribute will prevent the DOMContentLoaded
event from firing until the script has loaded and finished evaluating.
Resource: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attributes
* See the images at the bottom for feather explanation.
Event Listeners - Keep in mind that loading of the page has more, than one event:
"DOMContentLoaded"
This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for style sheets, images, and subframes to finish loading. At this stage you could programmatically optimize loading of images and CSS based on user device or bandwidth speed.
Executes after DOM is loaded (before images and CSS):
document.addEventListener("DOMContentLoaded", function(){
//....
});
Note: Synchronous JavaScript pauses parsing of the DOM.
If you want the DOM to get parsed as fast as possible after the user requested the page, you could turn your JavaScript asynchronous and optimize loading of style sheets
"load"
A very different event, **load**, should only be used to detect a *fully-loaded page*. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
Executes after everything is loaded and parsed:
document.addEventListener("load", function(){
// ....
});
MDN Resources:
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
https://developer.mozilla.org/en-US/docs/Web/Events/load
MDN list of all events:
https://developer.mozilla.org/en-US/docs/Web/Events
Event Listeners with readyStates - Alternative solution (readystatechange):
You can also track document.readystatechange states to trigger script execution.
// Place in header (do not use async or defer)
document.addEventListener('readystatechange', event => {
switch (document.readyState) {
case "loading":
console.log("document.readyState: ", document.readyState,
`- The document is still loading.`
);
break;
case "interactive":
console.log("document.readyState: ", document.readyState,
`- The document has finished loading DOM. `,
`- "DOMContentLoaded" event`
);
break;
case "complete":
console.log("document.readyState: ", document.readyState,
`- The page DOM with Sub-resources are now fully loaded. `,
`- "load" event`
);
break;
}
});
MDN Resources: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
Where to place your script (with & without async/defer)?
This is also very important to know where to place your script and how it positions in HTML as well as parameters like defer and async will affects script fetching, execution and HTML blocking.
* On the image below the yellow label “Ready” indicates the moment of ending loading HTML DOM. Then it fires: document.readyState = "interactive" >>> defered scripts >>> DOMContentLoaded event (it's sequential);
If your script uses async or defer read this: https://flaviocopes.com/javascript-async-defer/
And if all of the above points are still to early...
What if you need your script to run after other scripts are run, including those scheduled to run at the very end (e.g. those scheduled for the "load" event)? See Run JavaScript after all window.onload scripts have completed?
What if you need to make sure your script runs after some other script, regardless of when it is run? This answer to the above question has that covered too.
Reasonably portable, non-framework way of having your script set a function to run at load time:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
You can put a "onload" attribute inside the body
...<body onload="myFunction()">...
Or if you are using jQuery, you can do
$(document).ready(function(){ /*code here*/ })
or
$(window).load(function(){ /*code here*/ })
I hope it answer your question.
Note that the $(window).load will execute after the document is rendered on your page.
If the scripts are loaded within the <head> of the document, then it's possible use the defer attribute in script tag.
Example:
<script src="demo_defer.js" defer></script>
From https://developer.mozilla.org:
defer
This Boolean attribute is set to indicate to a browser that the script
is meant to be executed after the document has been parsed, but before
firing DOMContentLoaded.
This attribute must not be used if the src
attribute is absent (i.e. for inline scripts), in this case it would
have no effect.
To achieve a similar effect for dynamically inserted scripts use
async=false instead. Scripts with the defer attribute will execute in
the order in which they appear in the document.
Here's a script based on deferred js loading after the page is loaded,
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
Where do I place this?
Paste code in your HTML just before the </body> tag (near the bottom of your HTML file).
What does it do?
This code says wait for the entire document to load, then load the
external file deferredfunctions.js.
Here's an example of the above code - Defer Rendering of JS
I wrote this based on defered loading of javascript pagespeed google concept and also sourced from this article Defer loading javascript
Look at hooking document.onload or in jQuery $(document).load(...).
JavaScript
document.addEventListener('readystatechange', event => {
// When HTML/DOM elements are ready:
if (event.target.readyState === "interactive") { //does same as: ..addEventListener("DOMContentLoaded"..
alert("hi 1");
}
// When window loaded ( external resources are loaded too- `css`,`src`, etc...)
if (event.target.readyState === "complete") {
alert("hi 2");
}
});
same for jQuery:
$(document).ready(function() { //same as: $(function() {
alert("hi 1");
});
$(window).load(function() {
alert("hi 2");
});
NOTE: - Don't use the below markup ( because it overwrites other same-kind declarations ) :
document.onreadystatechange = ...
I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.
window.onload = function(){ doSomethingCool(); };
becomes...
window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
http://www.feedthebot.com/pagespeed/defer-loading-javascript.html
Working Fiddle on <body onload="myFunction()">
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction(){
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
If you are using jQuery,
$(function() {...});
is equivalent to
$(document).ready(function () { })
or another short hand:
$().ready(function () { })
See What event does JQuery $function() fire on? and https://api.jquery.com/ready/
document.onreadystatechange = function(){
if(document.readyState === 'complete'){
/*code here*/
}
}
look here: http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx
Just define <body onload="aFunction()"> that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }.
<body onload="myFunction()">
This code works well.
But window.onload method has various dependencies. So it may not work all the time.
Comparison
In below snippet I collect choosen methods and show their sequence. Remarks
the document.onload (X) is not supported by any modern browser (event is never fired)
if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one)
event handler given in <body onload="..."> (F) is wrapped by additional onload function
document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.
all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it).
solutions readystatechange (C,D) are executed multiple times by browser but for different document states:
loading - the document is loading (no fired in snippet)
interactive - the document is parsed, fired before DOMContentLoaded
complete - the document and resources are loaded, fired before body/window onload
<html>
<head>
<script>
// solution A
console.log(`[timestamp: ${Date.now()}] A: Head script`);
// solution B
document.addEventListener("DOMContentLoaded", () => {
print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);
});
// solution C
document.addEventListener('readystatechange', () => {
print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);
});
// solution D
document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};
// solution E (never executed)
window.onload = () => {
print(`E: <body onload="..."> override this handler`);
};
// solution F
function bodyOnLoad() {
print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);
infoAboutOnLoad(); // additional info
}
// solution X
document.onload = () => {print(`document.onload is never fired`)};
// HELPERS
function print(txt) {
console.log(txt);
if(mydiv) mydiv.innerHTML += txt.replace('<','<').replace('>','>') + '<br>';
}
function infoAboutOnLoad() {
console.log("window.onload (after override):", (''+document.body.onload).replace(/\s+/g,' '));
console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);
}
console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));
</script>
</head>
<body onload="bodyOnLoad()">
<div id="mydiv"></div>
<!-- this script must te at the bottom of <body> -->
<script>
// solution G
print(`[timestamp: ${Date.now()}] G: <body> bottom script`);
</script>
</body>
</html>
There is a very good documentation on How to detect if document has loaded using Javascript or Jquery.
Using the native Javascript this can be achieved
if (document.readyState === "complete") {
init();
}
This can also be done inside the interval
var interval = setInterval(function() {
if(document.readyState === 'complete') {
clearInterval(interval);
init();
}
}, 100);
Eg By Mozilla
switch (document.readyState) {
case "loading":
// The document is still loading.
break;
case "interactive":
// The document has finished loading. We can now access the DOM elements.
var span = document.createElement("span");
span.textContent = "A <span> element.";
document.body.appendChild(span);
break;
case "complete":
// The page is fully loaded.
console.log("Page is loaded completely");
break;
}
Using Jquery
To check only if DOM is ready
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
});
To check if all resources are loaded use window.load
$( window ).load(function() {
console.log( "window loaded" );
});
Use this code with jQuery library, this would work perfectly fine.
$(window).bind("load", function() {
// your javascript event
});
$(window).on("load", function(){ ... });
.ready() works best for me.
$(document).ready(function(){ ... });
.load() will work, but it won't wait till the page is loaded.
jQuery(window).load(function () { ... });
Doesn't work for me, breaks the next-to inline script. I am also using jQuery 3.2.1 along with some other jQuery forks.
To hide my websites loading overlay, I use the following:
<script>
$(window).on("load", function(){
$('.loading-page').delay(3000).fadeOut(250);
});
</script>
You can write a function on a specific script file and call it in to your body element using onload attribute.
Exemple:
<script>
afterPageLoad() {
//your code here
}
</script>
Now call your script into your html page using script tag:
<script src="afterload.js"></script>
into your body element; add onload attribute like this:
<body onload="afterPageLoad();">
As Daniel says, you could use document.onload.
The various javascript frameworks hwoever (jQuery, Mootools, etc.) use a custom event 'domready', which I guess must be more effective. If you're developing with javascript, I'd highly recommend exploiting a framework, they massively increase your productivity.
Using the YUI library (I love it):
YAHOO.util.Event.onDOMReady(function(){
//your code
});
Portable and beautiful! However, if you don't use YUI for other stuff (see its doc) I would say that it's not worth to use it.
N.B. : to use this code you need to import 2 scripts
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/event/event-min.js" ></script>
i can catch page load by this code
<script>
console.log("logger saber");
window.onload = (event) => {
console.log('page is fully loaded');
document.getElementById("tafahomNameId_78ec7c44-beab-40de-9326-095f474519f4_$LookupField").value = 1;;
};
</script>
My advise use asnyc attribute for script tag thats help you to load the external scripts after page load
<script type="text/javascript" src="a.js" async></script>
<script type="text/javascript" src="b.js" async></script>
<script type="text/javascript">
$(window).bind("load", function() {
// your javascript event here
});
</script>

How to trigger a javascript event when the page is loaded [duplicate]

I want to run a function when the page is loaded, but I don’t want to use it in the <body> tag.
I have a script that runs if I initialise it in the <body>, like this:
function codeAddress() {
// code
}
<body onLoad="codeAddress()">
But I want to run it without the <body onload="codeAddress()"> and I have tried a lot of things, e.g. this:
window.onload = codeAddress;
But it is not working.
So how do I run it when the page is loaded?
window.onload = codeAddress; should work - here's a demo, and the full code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
</script>
</head>
<body onload="codeAddress();">
</body>
</html>
Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.
I'd recommend this if you use native Javascript.
document.addEventListener('DOMContentLoaded', function() {
alert("Ready!");
}, false);
Alternate solution. I prefer this for the brevity and code simplicity.
(function () {
alert("I am here");
})();
This is an anonymous function, where the name is not specified.
What happens here is that, the function is defined and executed together.
Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.
Taking Darin's answer but jQuery style. (I know the user asked for javascript).
running fiddle
$(document).ready ( function(){
alert('ok');
});​
window.onload = function() { ... etc. is not a great answer.
This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours.
So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.
A more robust answer here:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Some code I have been using, I forget where I found it to give the author credit.
function my_function() {
// whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}
Hope this helps :)
Try readystatechange
document.addEventListener('readystatechange', () => {
if (document.readyState == 'complete') codeAddress();
});
where states are:
loading - the document is loading (no fired in snippet)
interactive - the document is parsed, fired before DOMContentLoaded
complete - the document and resources are loaded, fired before window.onload
<script>
document.addEventListener("DOMContentLoaded", () => {
mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;
});
window.onload = () => {
mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;
} ;
document.addEventListener('readystatechange', () => {
mydiv.innerHTML += `ReadyState: ${document.readyState} (timestamp: ${Date.now()})</br>`;
if (document.readyState == 'complete') codeAddress();
});
function codeAddress() {
mydiv.style.color = 'red';
}
</script>
<div id='mydiv'></div>
Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.
Example usage
// add reference to domReady script or place
// contents of script before here
function codeAddress() {
}
domReady(codeAddress);
window.onload will work like this:
function codeAddress() {
document.getElementById("test").innerHTML=Date();
}
window.onload = codeAddress;
<!DOCTYPE html>
<html>
<head>
<title>learning java script</title>
<script src="custom.js"></script>
</head>
<body>
<p id="test"></p>
<li>abcd</li>
</body>
</html>
As soon as the page load the function will be ran:
(*your function goes here*)();
Alternatively:
document.onload = functionName();
window.onload = functionName();
I believe this is the best way to maintain support across different versions of browsers
if (window.addEventListener) {
window.addEventListener("load", myFunction, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", myFunction);
}
else {
window.onload = myFunction; //will override previously attached event listeners.
}
Universal Cross-Browser Web Page Loader
I wrote a JavaScript page loader that should solve your issues loading a function after the page is loaded. This web page loader is 99.9% cross-browser compatible and works in many versions of browsers, old and new, unlike the other posts. Includes support for loading pages in nearly all browsers, including Internet Explorer 3-11, all Firefox and Chrome browsers, early Opera, all mobile browsers, Netscape 4 and 6 series, etc.
It will pick the fastest page load event or state check for a given browser and return a text string indicating JavaScript may safely process the Document Object Model (DOM). Should work in many legacy browsers, but test. Place your JavaScript functions or or library calls inside the "Start()" method below, so they are triggered as soon as the script says the web page or DOM is loaded in the browser.
As a side note, I recommend you place this code either:
In the head of your html page in a embedded <script> block as a synchronous script, which pauses the page to load early.
...or...
In a loaded external <script> tag file with the "async" attribute added so it loads quietly in parallel to your page but pauses html loading when download complete so it gets parsed and processed first.
The script should not render-block much if using these methods. You want this script ready when the web page DOM is first built and not after, especially since later states of the page could get delayed waiting for images, videos, and JavaScript API's to download.
// ======== AFTER PAGE LOADS CALL YOUR SCRIPTS HERE =========
function Start(status) {
// In most modern browsers the console should return:
// "Browser Loader : Document : DOMContentLoaded : interactive"
console.log(status);
// add your script calls here...
};
// ======== JAVASCRIPT PAGE LOADER =========
// Stokely Web Page loader, 2022
if (document.readyState) {
if (document.readyState === "complete" || document.readyState === "loaded") {
Start("Browser Loader : Document : readyState : complete");
} else {
if (window.addEventListener) {
// Never try and call 'DOMContentLoaded' unless the web page is still in an early loading state.
if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
window.addEventListener('DOMContentLoaded', function () {
// Most modern browsers will have the DOM ready after this state.
if (document.readyState === "interactive") {
Start("Browser Loader : Document : DOMContentLoaded : interactive");
} else if (document.readyState === "complete" || document.readyState === "loaded") {
Start("Browser Loader : Document : DOMContentLoaded : complete");
} else {
Start("Browser Loader : Document : DOMContentLoaded : load");
}
}, false);
} else {
// FALLBACK LOADER : If the readyState is late or unknown, go ahead and try and wait for a full page load event. Note: This function below was required for Internet Explorer 9-10 to work because of non-support of some readyState values! IE 4-9 only supports a "readyState" of "complete".
if (document.readyState === 'complete' || document.readyState === "loaded") {
Start("Browser Loader : Document : readyState : complete");
} else {
window.addEventListener('load', function () {
Start('Browser Loader : Window : Event : load');
}, false);
}
}
// If 'addEventListener' is not be supported in the browser, try the 'onreadystate' event. Some browsers like IE have poor support for 'addEventListener'.
} else {
// Note: document.onreadystatechange may have limited support in some browsers.
if (document.onreadystatechange) {
document.onreadystatechange = function () {
if (document.readyState === "complete" || document.readyState === "loaded"){
Start("Browser Loader : Document : onreadystatechange : complete");
}
// OPTIONAL: Because several versions of Internet Explorer do not support "interactive" or get flagged poorly, avoid this call when possible.
//else if (document.readyState === "interactive") {
//Start("Browser Loader : Document : onreadystatechange : interactive");
//}
}
} else {
// Note: Some browsers like IE 3-8 may need this more traditional version of the loading script if they fail to support "addeventlistener" or "onreadystate". "window.load" is a very old and very reliable page loader you should always fall back on.
window.onload = function() {
Start("Browser Loader : Window : window.onload (2)");
};
}
}
}
} else {
// LEGACY FALLBACK LOADER. If 'document.readyState' is not supported, use 'window.load'. It has wide support in very old browsers as well as all modern ones. Browsers Firefox 1-3.5, early Mozilla, Opera < 10.1, old Safari, and some IE browsers do not fully support 'readyState' or its values. "window.load" is a very old and very reliable page loader you should always fall back on.
window.onload = function () {
Start("Browser Loader : Window : window.onload (1)");
};
};
Note: When you run this script in a web browser, be sure to press F12 to pull up the browser tools screen and check the console tab to see the result. It will tell you at what stage the web page loader was triggered and when it called the 'Start()' script.
In most modern browsers (HTML5 or post-2010) it should be triggered as soon as the DOM or Document Object Model of HTML markup is rendered but the rest of the web page resources, CSS, images, video, and other files are still loading. In modern browsers this is usually between a readystate of "interactive" and "complete" and the DOM is built but the browser is still downloading other resource files. This allows your JavaScript to access and start manipulating the HTML tree or DOM very very early.
Older browsers like Internet Explorer v. 3-8 or Netscape, do not understand the advanced DOM checks so would require the full or "complete" load of the DOM and all page resources before calling your JavaScript.

jquery not visible after dynamically adding it in script element

I have a script that dynamically loads jQuery, by inserting it in <head> element:
// pseudo code
headElelement.insertBefore(script, firstChild);
However, immediately after that call, I start to use jQuery, but at that moment it is undefined. How is that possible ?
That's because jQuery is not fully loaded yet. You may need to execute your jQuery code only after jQuery has been loaded by attaching an event handler to the onload event of your dynamically created script element as shown below.
script.onload = function() {
// Put your jQuery code here.
console.log(jQuery);
};
Cross-Browser solution for supporting older browsers like IE8 and below:
script.onload = script.onreadystatechange = function(event) {
event = event || window.event;
if (event.type === "load" || (/loaded|complete/.test(script.readyState))) {
script.onload = script.onreadystatechange = null;
// Put your jQuery code here.
console.log(jQuery);
}
};
If you would post your relevant code it would be easier ;-) but anyways, this is one possible way of doing it:
<html>
<head>
<script type="text/javascript" src="path_to_js/jquery.js"></script>
<script type="text/javascript" src="path_to_js/your_js_code.js"></script>
...
</head>...
and in the file your_js_code.js you'll have:
... /* All your modules and functions here */
/* DOM loading ready */
$(document).ready(function () {
call_your_methods_here();
});
By the way, it is usually better to load your JS files at the very end of the <body> in the HTML, that way your HTML starts displaying first and the user "sees" your page faster, while the JS code is still loading.

Dom loaded event cross borwser native javascript code

I'm working without the JavaScript framework, but I want to call a function just when the DOM is loaded.
I can't/don't want to use the attribute onload on the <body> tag.
I think http://code.google.com/p/domready/ is exactly what you're looking for.
If you are ever writing your own JavaScript file that cannot depend on
the existing libraries out there and would like to execute only after
the page is loaded, this library is for you.
Simply do this:
<html lang="en">
<head>
<script src="domready.js" type="application/javascript"></script>
<script type="application/javascript">
DomReady.ready(function() {
alert('dom is ready');
});
</script>
</head>
<body>
</body>
</html>
Here is the code:
in non-IE browsers, use DOMContentLoaded event
in IE top frame use scroll hack (see _readyIEtop)
in IE frame, simply use onload
var onready = function(handler) {
// window is loaded already - just run the handler
if(document && document.readyState==="complete") return handler();
// non-IE: DOMContentLoaded event
if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
// IE top frame: use scroll hack
else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
// IE frame: use onload
else if(window.attachEvent) window.attachEvent("onload",handler);
};
// IE stuff
var _readyQueue = [];
var _readyIEtop = function() {
try {
document.documentElement.doScroll("left");
var fn; while((fn=_readyQueue.shift())!=undefined) fn();
}
catch(err) { setTimeout(_readyIEtop,50); }
};
jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.
var test = function() { alert("ok"); }
onready(test);
Well, I'm afraid cross-browser and DOM loaded don't go together easily. By recommendation is Ryan Morr's ondomready (https://github.com/ryanmorr/ondomready) but there are a ton of alterntives.

How to run a function when the page is loaded?

I want to run a function when the page is loaded, but I don’t want to use it in the <body> tag.
I have a script that runs if I initialise it in the <body>, like this:
function codeAddress() {
// code
}
<body onLoad="codeAddress()">
But I want to run it without the <body onload="codeAddress()"> and I have tried a lot of things, e.g. this:
window.onload = codeAddress;
But it is not working.
So how do I run it when the page is loaded?
window.onload = codeAddress; should work - here's a demo, and the full code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
</script>
</head>
<body onload="codeAddress();">
</body>
</html>
Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.
I'd recommend this if you use native Javascript.
document.addEventListener('DOMContentLoaded', function() {
alert("Ready!");
}, false);
Alternate solution. I prefer this for the brevity and code simplicity.
(function () {
alert("I am here");
})();
This is an anonymous function, where the name is not specified.
What happens here is that, the function is defined and executed together.
Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.
Taking Darin's answer but jQuery style. (I know the user asked for javascript).
running fiddle
$(document).ready ( function(){
alert('ok');
});​
window.onload = function() { ... etc. is not a great answer.
This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours.
So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.
A more robust answer here:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Some code I have been using, I forget where I found it to give the author credit.
function my_function() {
// whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}
Hope this helps :)
Try readystatechange
document.addEventListener('readystatechange', () => {
if (document.readyState == 'complete') codeAddress();
});
where states are:
loading - the document is loading (no fired in snippet)
interactive - the document is parsed, fired before DOMContentLoaded
complete - the document and resources are loaded, fired before window.onload
<script>
document.addEventListener("DOMContentLoaded", () => {
mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;
});
window.onload = () => {
mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;
} ;
document.addEventListener('readystatechange', () => {
mydiv.innerHTML += `ReadyState: ${document.readyState} (timestamp: ${Date.now()})</br>`;
if (document.readyState == 'complete') codeAddress();
});
function codeAddress() {
mydiv.style.color = 'red';
}
</script>
<div id='mydiv'></div>
Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.
Example usage
// add reference to domReady script or place
// contents of script before here
function codeAddress() {
}
domReady(codeAddress);
window.onload will work like this:
function codeAddress() {
document.getElementById("test").innerHTML=Date();
}
window.onload = codeAddress;
<!DOCTYPE html>
<html>
<head>
<title>learning java script</title>
<script src="custom.js"></script>
</head>
<body>
<p id="test"></p>
<li>abcd</li>
</body>
</html>
As soon as the page load the function will be ran:
(*your function goes here*)();
Alternatively:
document.onload = functionName();
window.onload = functionName();
I believe this is the best way to maintain support across different versions of browsers
if (window.addEventListener) {
window.addEventListener("load", myFunction, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", myFunction);
}
else {
window.onload = myFunction; //will override previously attached event listeners.
}
Universal Cross-Browser Web Page Loader
I wrote a JavaScript page loader that should solve your issues loading a function after the page is loaded. This web page loader is 99.9% cross-browser compatible and works in many versions of browsers, old and new, unlike the other posts. Includes support for loading pages in nearly all browsers, including Internet Explorer 3-11, all Firefox and Chrome browsers, early Opera, all mobile browsers, Netscape 4 and 6 series, etc.
It will pick the fastest page load event or state check for a given browser and return a text string indicating JavaScript may safely process the Document Object Model (DOM). Should work in many legacy browsers, but test. Place your JavaScript functions or or library calls inside the "Start()" method below, so they are triggered as soon as the script says the web page or DOM is loaded in the browser.
As a side note, I recommend you place this code either:
In the head of your html page in a embedded <script> block as a synchronous script, which pauses the page to load early.
...or...
In a loaded external <script> tag file with the "async" attribute added so it loads quietly in parallel to your page but pauses html loading when download complete so it gets parsed and processed first.
The script should not render-block much if using these methods. You want this script ready when the web page DOM is first built and not after, especially since later states of the page could get delayed waiting for images, videos, and JavaScript API's to download.
// ======== AFTER PAGE LOADS CALL YOUR SCRIPTS HERE =========
function Start(status) {
// In most modern browsers the console should return:
// "Browser Loader : Document : DOMContentLoaded : interactive"
console.log(status);
// add your script calls here...
};
// ======== JAVASCRIPT PAGE LOADER =========
// Stokely Web Page loader, 2022
if (document.readyState) {
if (document.readyState === "complete" || document.readyState === "loaded") {
Start("Browser Loader : Document : readyState : complete");
} else {
if (window.addEventListener) {
// Never try and call 'DOMContentLoaded' unless the web page is still in an early loading state.
if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
window.addEventListener('DOMContentLoaded', function () {
// Most modern browsers will have the DOM ready after this state.
if (document.readyState === "interactive") {
Start("Browser Loader : Document : DOMContentLoaded : interactive");
} else if (document.readyState === "complete" || document.readyState === "loaded") {
Start("Browser Loader : Document : DOMContentLoaded : complete");
} else {
Start("Browser Loader : Document : DOMContentLoaded : load");
}
}, false);
} else {
// FALLBACK LOADER : If the readyState is late or unknown, go ahead and try and wait for a full page load event. Note: This function below was required for Internet Explorer 9-10 to work because of non-support of some readyState values! IE 4-9 only supports a "readyState" of "complete".
if (document.readyState === 'complete' || document.readyState === "loaded") {
Start("Browser Loader : Document : readyState : complete");
} else {
window.addEventListener('load', function () {
Start('Browser Loader : Window : Event : load');
}, false);
}
}
// If 'addEventListener' is not be supported in the browser, try the 'onreadystate' event. Some browsers like IE have poor support for 'addEventListener'.
} else {
// Note: document.onreadystatechange may have limited support in some browsers.
if (document.onreadystatechange) {
document.onreadystatechange = function () {
if (document.readyState === "complete" || document.readyState === "loaded"){
Start("Browser Loader : Document : onreadystatechange : complete");
}
// OPTIONAL: Because several versions of Internet Explorer do not support "interactive" or get flagged poorly, avoid this call when possible.
//else if (document.readyState === "interactive") {
//Start("Browser Loader : Document : onreadystatechange : interactive");
//}
}
} else {
// Note: Some browsers like IE 3-8 may need this more traditional version of the loading script if they fail to support "addeventlistener" or "onreadystate". "window.load" is a very old and very reliable page loader you should always fall back on.
window.onload = function() {
Start("Browser Loader : Window : window.onload (2)");
};
}
}
}
} else {
// LEGACY FALLBACK LOADER. If 'document.readyState' is not supported, use 'window.load'. It has wide support in very old browsers as well as all modern ones. Browsers Firefox 1-3.5, early Mozilla, Opera < 10.1, old Safari, and some IE browsers do not fully support 'readyState' or its values. "window.load" is a very old and very reliable page loader you should always fall back on.
window.onload = function () {
Start("Browser Loader : Window : window.onload (1)");
};
};
Note: When you run this script in a web browser, be sure to press F12 to pull up the browser tools screen and check the console tab to see the result. It will tell you at what stage the web page loader was triggered and when it called the 'Start()' script.
In most modern browsers (HTML5 or post-2010) it should be triggered as soon as the DOM or Document Object Model of HTML markup is rendered but the rest of the web page resources, CSS, images, video, and other files are still loading. In modern browsers this is usually between a readystate of "interactive" and "complete" and the DOM is built but the browser is still downloading other resource files. This allows your JavaScript to access and start manipulating the HTML tree or DOM very very early.
Older browsers like Internet Explorer v. 3-8 or Netscape, do not understand the advanced DOM checks so would require the full or "complete" load of the DOM and all page resources before calling your JavaScript.

Categories

Resources