Defer parsing of JavaScript - Google Page Speed - javascript

All of my JavaScript files are already at the bottom but Google Page Speed is giving this suggestion to improve speed:
Defer parsing of JavaScript
88.6KiB of JavaScript is parsed during initial page load. Defer
parsing JavaScript to reduce blocking of page rendering.
http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
(76.8KiB) http://websiteurl/js/plugins.js (11.7KiB) http://websiteurl/
(109B of inline JavaScript)
This is the my html (example)
<html>
<head>
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script>
<script src="js/plugins.js"></script>
<script>$(document).ready(function() {
$("#various2").fancybox({
'width': 485,
'height': 691,
});
});</script>
</body>
</html>
What should I do to increase performance by using defer?
Is it only for Google chrome or for all?

If you're looking for page performance then first and foremost you should move those scripts to the bottom of your page to allow the other assets to load.
Also use dns prefetch in the head to set the base domain for google-code
<link rel="dns-prefetch" href="//ajax.googleapis.com">
Since this is just a small piece of code, you could simply add it to your plugins.js file at the bottom then defer the plugins file.
<script src="js/plugins.js" defer></script>
That's what I'd do anyway, all my sites are optimized to 98 and 97 respectively in yslow and page speed.
Hope it helps.
-V

Add in <script type="text/javascript" defer="defer"> tag like that it works for me.
<script type="text/javascript" defer="defer" src="<?php echo $this->getSkinUrl();?>js/jquery.bxslider.js"></script>

I see this is an old question, but since I was looking for a good answer myself, I am going to share the method I currently use.
As far as inline Javascript is concerned, what I do is change all the type attributes to text/deferred-javascript, or something similar, so that the code within the script tag is not evaluated during page load. Then I attach a function to the page onload event; said function finds all the scripts matching the type above and evaluates the code inside using eval(). I know in general eval() is evil but it seems to be helpful here.
For external Javascript files, I do something very similar. Instead of adding the script tags to the page, I record them and insert them one-by-one after page load has completed.
One problem I'm having is that if one of the inline deferred Javascript contains an error (say a parse error), the subsequent scripts are not loaded (but that might depend on my current implementation).

That's probably a generic response/suggestion for when it encounters a certain level of performance.
Although, it specifically mentions jQuery, a plugin, and 109 bytes of inline JavaScript. Do you have any inline JavaScript? Are you also placing your JavaScript includes at the bottom of the <body>?
Example
Loading Performance article
EDIT:
Based on recently posted HTML...
As a test, remove these two items to see if it makes any difference:
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script>
Also, the warning message mentions 109 bytes of inline JS, yet I don't see anything like that in the HTML you've posted.

Hi recently we have created an opensource nodejs framework called "elegant framework" that help you building fast web application and we succeeded to get 100% google page speed in both desktop and mobile in all pages :
you can check it at:
https://developers.google.com/speed/pagespeed/insights/?url=getelegant.com
there is a lot of things you can learn from it by viewing the page source also if anything you cannot understand please comment so i can help you with
so far you can try this method:
// Load script element as a child of the body
function loadJS(src, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
if (callback) {
callback();
}
}
};
} else { //Others
script.onload = function () {
if (callback) {
callback();
}
};
}
script.src = src;
document.body.appendChild(script);
}
// Load style element as a child of the body
function loadCSS(href,callback) {
var element = document.createElement("link");
element.rel = "stylesheet";
if (element.readyState) { //IE
element.onreadystatechange = function () {
if (element.readyState == "loaded" || script.readyState == "complete") {
element.onreadystatechange = null;
if (callback) {
callback();
}
}
};
} else { //Others
element.onload = function () {
if (callback) {
callback();
}
};
}
element.href = href;
document.body.appendChild(element);
}
// Load All Resources
function loadResources() {
// css
loadCSS("/compressed/code-mirror-style.css?please1");
loadCSS("/compressed/all.css?please2");
// js
loadJS("/compressed/code-mirror.js", function () {
loadJS("/compressed/common.js", function () {
$("[data-lang]").each(function () {
var code = $(this).addClass("code").text();
$(this).empty();
var myCodeMirror = CodeMirror(this, {
value: code,
mode: $(this).attr("data-lang"),
lineNumbers: !$(this).hasClass('inline') && !$(this).hasClass('no-numbers'),
readOnly: true
});
});
});
});
}
// Check for browser support of event handling capability
if (window.addEventListener) {
window.addEventListener("load", loadResources, false);
} else if (window.attachEvent) {
window.attachEvent("onload", loadResources);
} else {
window.onload = loadResources
}

Related

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.

Loading javascript after all other scripts

I'm using a CMS which has a lot of javascript, both in size and quantity.
I'm trying to add iframe.ly to it so that card previews can be generated for posted URLs.
It works perfectly fine on all pages except for ones that have posts (which are the most important), since posts are loaded via a javascript called stream, and it seems that iframely's script is loading before the stream.
I know this is the issue because I can trigger the script directly using iframely.load(), which does the trick. But I need this to happen automatically on every page load.
This is the script that I added to my header: <script defer charset="utf-8" src="//cdn.iframe.ly/embed.js?key=[my-api-key]" ></script>
Iframely offers another option in their docs, which is this:
<script defer type="text/javascript">
function loadIframelyEmbedJs() {
// Replace 'iframe.ly' with your custom CDN if available.
if (document.querySelectorAll("[data-iframely-url]").length === 0
&& document.querySelectorAll("iframe[src*='iframe.ly']").length === 0) return;
var iframely = window.iframely = window.iframely || {};
if (iframely.load) {
iframely.load();
} else {
var ifs = document.createElement('script'); ifs.type = 'text/javascript'; ifs.async = true;
ifs.src = ('https:' == document.location.protocol ? 'https:' : 'http:') + '//cdn.iframe.ly/embed.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ifs, s);
}
}
// Run after DOM ready.
loadIframelyEmbedJs();
</script>
This is supposed to make iframely "load only when required", as in when embeds are detected in the page. But that doesn't fix the problem either because that too is loaded before the stream.
I don't mind using jquery if needed.
Edit: Removed mentions of the CMS. It adds unnecessary confusion. This is a javascript question.
Fixed it by wrapping it in this function:
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "//cdn.iframe.ly/embed.js?key=[my-api-key]";
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>
Strange that it's so hard to achieve something like this, or find information on how to do it.
Source: Some SEO website that I can't find anymore.

Loading inline jQuery scripts along with deferred and async scripts

I am working on a website and working on its Page Speed Insights and have a
Eliminate render-blocking JavaScript and CSS in above-the-fold content
So basically what happen is I have two external javascript import on top of the page which is:
<script src="/remotestaff_2015/js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="/remotestaff_2015/js/bootstrap.min.js" type="text/javascript"></script>
This website has lot of javascripts but some are at the bottom of the page after the <body> tag. So my problem is those two on the top. To fix the render block I already searched on google and found out that I can use the defer or async attribute. My problem is that there are some modules on the website that has inline javascripts like:
<script type="text/javascript">
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
if ($("#wrapper").hasClass("toggled")) {
$(".color-fade").css("opacity", ".5");
} else {
$(".color-fade").css("opacity", "1");
}
});
So if I put defer on my jquery file I'll have an error on my inline javascripts because it will load without the jquery loaded yet. Is there a way to fix this inline scripts or somehow make them run after the deferred jquery or other js files has been loaded? I don't want to put those inline scripts in other file.
According to MDN:
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.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
Therefore let your inline script wait for the document and the deferred scripts to be loaded. The DOMContentLoaded event will fire when that has happened:
<script>
document.addEventListener('DOMContentLoaded', function() {
// Inline scripts go here
});
</script>
Notice that the $(document).ready(function() is not required any more, because that would wait for the same event (DOMContentLoaded).
you can load your js dynamically in
$(window).bind("load", function() {
// code here
});
for dynamically loading scripts you ca use code
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
Please let me know if it helped you.
I would do this to make everything clean. Load jQuery file without defer and define menu toggling event in HTML head.
<script src="/remotestaff_2015/js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
// option 1
/* $('#menu-toggle').click(function() {
// your code
}); */
});
// option 2
$(document).on('click', '#menu-toggle', function() {
// your code
});
</script>
Now you can render the element anywhere in HTML body or even from AJAX callback.

Delay Loading Javascript to speed my Joomla

I'm using joomla site, and Forced to use extra java script.
My Question is:
How to force loading the javascript ONLY after page complete
I dont mean DELAY them, But make them in Queue till the page complete loading.
I tried many of links tutorial but nothing helps me.
Please,
Would you provide correct example in order to make me understand.
Example to JS file I inserted to buttom of my page:
<script src="/js/easing.js" type="text/javascript"></script>
Can you provide Jquery code to force all those script to wait till the page load complete?
Thank you
Tariq
Ales Kotnik answer's in great, and also if you want to do it in your own specifiec time, you can do something like that:
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
this will load a script only when you call it, and then you activate it like this:
<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>
Use <script src="..." async="async"/>. In modern browsers (HTML5)it will spawn fetching javascript files separately and won't delay loading of your HTML. You can just put script tags at the end of your <body>.

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