I am working on a page where I have to make interface changes on window.load. I am using
jQuery(window).load(function () {
//all my code goes here
});
It works fine most of the time but very randomly few time, it doesn't execute at at all. I don't even get any error in the console. It is so random that I can't event reproduce this problem. My question is that is there anything more reliable than the window.onload event to make interface changes?
I also apologies in advance that I can't share the link.
You can avoid jQuery and use plain javascript. You can use DOMContentLoad (https://developer.mozilla.org/pt-BR/docs/Web/Events/DOMContentLoaded) event. Or addEventListener
window.addEventListener('load', callback)
Take a read here.
Related
The $(document).ready() function is not very good if the page fails to load completely, or if it's loading very slowly.
How could I modify the element as soon as it has been created? Some delay is fine, as long as it's not multiple seconds.
I am using Greasemonkey also, if that matters. But I would be interested in a solution that works outside of Greasemonkey too.
I wouldn't want to break the performance on the webpage either.
Edit: I do not own the website I am modifying. Therefore I cannot put any code there manually.
I tried window.onload = function(){} instead of $(document).ready(function(){}) but i noticed the jquery version was twice as fast.
Looks like people did not understand question before they downvoted.
I misunderstood your problem, so am rewriting my answer completely.
If $(document).ready() is too slow for you, then onload will definitely be too slow for you. Without a snippet of code, I can't give you something specific, but this should work for you:
var checkIfExists = setInterval(function() {
var exists = document.getElementById("foo");
if (exists) {
clearInterval(checkIfExists);
doStuff(exists);
}
}, 25);
function doStuff(element) {
element.innerHTML = "bar";
}
Make sure not to put this inside of any onload or ondomready / $(document).ready() event handlers.
Once this script loads, it will check if an element with the id of foo exists every 25 milliseconds. Once it can successfully find foo, it stops searching and runs function doStuff. Now, I don't know if what you want to modify actually has an id or not, so you will have to figure out exactly how to search for it.
I'm sure you know this, but I wanted to mention that the number of times the interval runs is heavily dependent upon where the script is loaded in the html document. For example, if it is at the bottom of the document it may only run once. If it is in the header, it will run just until foo is loaded.
Here is a working example with JSFiddle.
I was inspecting my source on a page that uses Rafael js and some elements have "element.click(handler)"
on several elements however I never see any "onclick=handler()" or any events on the svg elements, so how does it know to call handler when the element is clicked?
The reason I ask is because one of my elements works the first time you click on it, but doesn't work after that. There is no js error, it just doesn't call the method anymore and I don't know how to debug this, since I can't tell if the onclick is gone from the element or what.
Any ideas?
Thanks
You can not see for eg. because he is not using that coding.
He uses his own addEvent function that uses addEventListener(FF) or attachEvent (MS) depending on what browser that code runs.
On FF/chrome install firebug plugin and use debugger; statement.
Use console.log(); or alert() to represent yourself what's going on in that handler function.
And take a good look at 'this' if you are using it. 'This' changes scope depending on fun or object.
In one of my projects, I have window.location.href='index.php'. That project is big and it is absurd to paste whole code.
In it I have attached event handlers, some AJAX calls and few custom animations. I had solved this in other manner, but I would appreciated few suggestions why that command didn't work?
When I used FireBug to inspect code, and go step by step, redirection was successful.
Try to add your code to the onload handler or, if you use jQuery, in the ready handler:
$(document).ready(function() {
window.location.href='index.php';
});
I'm using window.onload to call my JavaScript code that has to be executed after the page is fully loaded. From what I read this is the recommended method to call such scripts.
However, it does not work for some Ajax sites, www.bing.com for instance - window.onload is called before the pages is fully rendered.
Any suggestions?
The short answer is that there's no general way to solve this problem (right now).
The definition of a "page" is pretty fungible when AJAX comes into play - it's pretty hard to tell the difference between AJAX that is intended to be part of the initial page load, and that which might not be. So, browsers are left on their own to determine when window.onload() should be fired, and it doesn't always end up where you want.
Luckily, most people don't need a general solution, but rather a specific one. If you care about bing.com, then you can probably look at how bing.com works and design your code to trigger when the site reaches a state that you find acceptable.
I've wrestled with this a couple of times, and my usual reason for needing some sort of onload event triggering is to be able to interact with the HTML DOM and have getElementById, getElementsByTagName, or various other DOM selectors, return something other than nothing.
Once again, I'm not sure of the exact problem you are trying to solve, but if you must use some sort of onload, and it's because of DOM traversal of some kind, you can cheat a bit with the following sort of code:
window.onload = pageChecker;
function pageChecker() {
// Onload has fired, but we don't trust it.
// Check to see if our deepest nested element can be found
var testElement = document.getElementById("importantElement");
if ( !testElement ) {
// Try again in a bit, adjust timeout to what your users
// can tolerate
setTimeout(pageChecker, 50);
}
else {
//
// ... the element exists, run important code below ...
//
}
}
You might be able to listen for changes and requests by globally listening for DOMSubtreeModified and readystatechange events, and use those events instead of the load event for whatever you are trying to do.
I'd recomend using jQuerys $(...).ready() method.
In addition to the answer from Rasmus Kaj and if you are using jQuery, I would direct you to take a look at Global Ajax Event Handlers.
jQuery.fn.ajaxComplete (http://api.jquery.com/ajaxcomplete/)
jQuery.fn.ajaxStop (http://api.jquery.com/ajaxstop/)
Note, that this has nothing to do with the native onload event.
I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).
Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?
For example:
function updateDOM(id) {
// updates the id element based on form state
}
should I invoke it via:
window.onload = function() { updateDOM("myElement"); };
or:
<div id="myElement">...</div>
<script language="javascript">
updateDOM("myElement");
</script>
The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.
Any thoughts? Is one version really better than the other?
The onload event is considered the proper way to do it, but if you don't mind using a javascript library, jQuery's $(document).ready() is even better.
$(document).ready(function(){
// manipulate the DOM all you want here
});
The advantages are:
Call $(document).ready() as many times as you want to register additional code to run - you can only set window.onload once.
$(document).ready() actions happen as soon as the DOM is complete - window.onload has to wait for images and such.
I hope I'm not becoming The Guy Who Suggests jQuery On Every JavaScript Question, but it really is great.
I've written lots of Javascript and window.onload is a terrible way to do it. It is brittle and waits until every asset of the page has loaded. So if one image takes forever or a resource doesn't timeout until 30 seconds, your code will not run before the user can see/manipulate the page.
Also, if another piece of Javascript decides to use window.onload = function() {}, your code will be blown away.
The proper way to run your code when the page is ready is wait for the element you need to change is ready/available. Many JS libraries have this as built-in functionality.
Check out:
http://docs.jquery.com/Events/ready#fn
http://developer.yahoo.com/yui/event/#onavailable
Definitely use onload. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
Some JavaScript frameworks, such as mootools, give you access to a special event named "domready":
Contains the window Event 'domready', which will execute when the DOM has loaded. To ensure that DOM elements exist when the code attempting to access them is executed, they should be placed within the 'domready' event.
window.addEvent('domready', function() {
alert("The DOM is ready.");
});
window.onload on IE waits for the binary information to load also. It isn't a strict definition of "when the DOM is loaded". So there can be significant lag between when the page is perceived to be loaded and when your script gets fired. Because of this I would recommend looking into one of the plentiful JS frameworks (prototype/jQuery) to handle the heavy lifting for you.
#The Geek
I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).
In Firefox, onload is called when the DOM has finished loading regardless of how you navigated to a page.
While I agree with the others about using window.onload if possible for clean code, I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).
Edit: I could have that backwards.
In some cases, it's necessary to use inline script when you want your script to be evaluated when the user hits the back button from another page, back to your page.
Any corrections or additions to this answer are welcome... I'm not a javascript expert.
My take is the former becauase you can only have 1 window.onload function, while inline script blocks you have an n number.
onLoad because it is far easier to tell what code runs when the page loads up than having to read down through scads of html looking for script tags that might execute.