$(window).load() in IE? - javascript

Recently I ran into a mysterious problem that IE (6-8) is keeping throwing me an error. I don't know if this is the problem, but I think it is.
Open up the F12 developer tools in a jQuery included website, enter
$(window).load(function(){
alert("Wont able to see me");
});
And an error will popup:
"Unable to get value of the property 'slice': object is null or undefined"
Did I do anything wrong, or anything else???

I recently found a work-around for IE not recognizing $(window).load()...
window.onload = function() {
alert("See me, hear me, touch me!");
};
This is a little different than $(function(){}) as it executes after all elements are loaded as opposed to when the DOM is ready.
I recently implemented this in another project and it worked wonderfully.

For anyone still running into this, IE11 (only one I tested) does not fire the the load event if the listener is inside of the jquery ready function. So pull the load function outside of the ready function and it will fire in IE11.
//this is bad
$(() => { //jquery ready
window.onload = () => { //wont fire in IE
cosole.log('window loaded');
}
});
//this is good
$(() => { //jquery ready
cosole.log('dom ready');
});
window.onload = () => { //will fire in IE
cosole.log('window loaded');
}

The latest jQuery (1.7.1) with IE10 and IE9 does not produce such an error for me.
As a side note; If you wish to execute something when the dom is ready;
Try this way;
$(function(){
alert("Wont able to see me");
});
I believe this is the standard convention for attaching a function to domready event.
Reference: jQuery Documentation

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!");
});

The "document.ready()" function not firing on Chrome Mobile (android)

I have jQuery-2.1.4.min.js called before the tag, but when I write something like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
alert('hi, world.');
});
</script>
On my PC it is fired of course, but on ten different Android devices it just does not. This is purely HTML/CSS/jQuery rendered site (no phonegap, or anything).
My goal was to have a button do ajax request after it's being tapped, but I can't even test that, because the .ready() function is not firing at all on mobile chrome.
The jQuery is being served from the official CDN, any help would be very much appreciated.
Tried both:
$(function() {
alert('hi, world.');
});
And
jQuery(document).ready(function() {
alert('hi, world.');
});
Same thing.
As suggested I also tried:
window.onload = function()
{
if (window.jQuery)
{
alert('jQuery is loaded');
}
else
{
alert('jQuery is not loaded');
}
}
And it alerts 'jQuery is loaded'.
As per jQuery docs it says: "Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute" - which would mean that DOM is not ready for JavaScript code to execute? But when I try like:
<script type="text/javascript">
alert('hi world');
</script>
It executes on mobile Chrome.
Okay, after extensive investigation it seems that JS breaks on mobile chrome if you have document.ready() function twice, I had one in my core.js file and one in-line on the page.
It works okay on PC (all browsers), but on mobile it works up to the point of second ready() call and breaks all JS after that.
Hopefully this saves some time to others in the future.
JS breaks on mobile view becouse same js use multiple time in file. Check and remove redundancy.

Selector only working after inspecting/selecting element

I have this code here:
$(document).ready(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('Hello'); });
});
The weird thing I can't explain is, that when I execute the selector once I'm in the console when reaching the debugger statement, it returns an empty array, []
But when I step out and go on the page, then hit Ctrl-Shift-C in Chrome to start inspecting and click on some of the div's that have the ID I'm looking for then execute the selector again in the console, now I have the elements I'm expecting.
I have even tried this here so to validate whether it was an async. loading issue (this is a system over which I don't have all the control). but still, when reaching the debugger, the selector doesn't work - even after waiting 10 seconds (which then I'm pretty sure the div's are there). I still have to go in inspector so jQuery recognize the elements.
$(document).ready(function() {
//debugger;
setTimeout(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('allo'); });
}, 10000);
});
Why would jQuery only be aware of elements that I've clicked on with Chrome's inspector ?
I know it's a bit late but when you open Dev Tools in Chrome the execution context is set to top. If your controls are located within an iFrame, that is a different context, not accessible from top. Use the dropdown to select your iFrame's context and your jQuery will return an element.
The reason it works when you inspect an element, is Chrome has selected the execution context for you already.
Discussion about iFrame context in Dev Tools
Using the "on", it works even if the element exists after the page loads.
$(document).ready(function(){
//$("div[id^='stage_']").click( function (e) { alert('Hello'); });
$("body").on('click','div[id^="stage_"]', function (e) { alert('Hello'); });
$('body').html('<div id="stage_1">teste1</div>' +
'<div id="stage_2">teste2</div>' +
'<div>blabla</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
doc: http://api.jquery.com/on/

$(window).focus() runs twice for each focus

I'm not sure why this happens and I would love to get an explanation.
Using jquery's focus method I bind to the window focus event.
This is a working example (copy paste into a html file and open in a browser. Doesn't work in jsfiddle or jsbin, for some reason)
<!DOCTYPE html>
<html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script></head>
<body>
<p1>Here:</p1>
<div id="here" >Why</div>
</body>
<script>
$(window).load(function() {
$(window).focus(function() {console.log("focus");});
$(window).blur(function() {console.log("blur");});
});
</script>
</html>
When the browser regains focus the function runs twice and 'focus` is printed into the console twice.
Any idea why this happens?
The end goal, btw, is to stop a timer from running whenever the user leaves the browser to an app or another tab.
UPDATE
Running on the latest (dev) version of chrome. I'll test it on firefox and write if it's different there.
UPDATE 2
Interesting fact - Doesn't happen on firefox. Maybe its a bug with chrome.
I had this same problem. My fix for this was using lodash's debounce() function (https://lodash.com/docs/#debounce). This was my fix:
var debouncedFocus = _.debounce(() => {
console.log('focussed');
}, 250, {leading: true, trailing: false});
$(window).on('focus', debouncedFocus);
live() has been deprecated. Use on() instead.
$(window).on("focus", function(){ alert("focus!"); });
You could try using the live() function.
$(window).live("focus", function(){ alert("focus!"); });
Maybe load() is called twice? You can register these events without .load(). Try this:
<script>
$(window).focus(function() {console.log("focus");});
$(window).blur(function() {console.log("blur");});
</script>
Which browser ? Seems to run fine for me.
As a precaution, you can use a javascript variable to make it run only once.
<script>
var isFocused = false;
$(window).load(function() {
$(window).focus(function() {
if(isFocused)
return;
console.log("focus");
isFocused = true;
});
$(window).blur(function() {
console.log("blur");
isFocused = false;
});
});
</script>
If you're simultaneously using Underscore, you can use the _.debounce() method to clamp down repeated events to a single event.

Categories

Resources