For some reason, IE9 is not running my JavaScript code onload when the browser is launched for the first time that session. It seems to only run onload after the user refreshes the page. It will also run the JavaScript when the debug console is open.
How do I make it so the JavaScript runs onload after the browser is open? Is this just a bug of IE9?
I'll restate this so you understand: The code DOESN'T run if you go to the site after launching a new browser session. The code DOES run if you open the site in a new tab, or reload the page, or open the debug console
Here is the function I use to run my script onload (which works fine in NORMAL browsers):
(function (i) {
var u = navigator.userAgent;
var e = /*#cc_on!#*/
false;
var st = setTimeout;
if (/webkit/i.test(u)) {
st(function () {
var dr = document.readyState;
if (dr == "loaded" || dr == "complete") {
i()
} else {
st(arguments.callee, 10);
}
}, 10);
} else if ((/mozilla/i.test(u) && !/(compati)/.test(u)) || (/opera/i.test(u))) {
document.addEventListener("DOMContentLoaded", i, false);
} else if (e) {
(function () {
var t = document.createElement('doc:rdy');
try {
t.doScroll('left');
i();
t = null;
} catch (e) {
st(arguments.callee, 0);
}
})();
} else {
window.onload = i;
}
})(init); //init is the function to call onload
I had the exact same issue that you had. I had a set of images that I wanted to ensure were preloaded before I began starting a slideshow. I was making use of
$(window).load(function(){
//All my code
});
And this is exactly what I was facing.
When I copied and pasted the URL in IE, the onload event did not seem to fire.
If I open the console using F12 and then past the URL in the browser and pressed enter, the everything seemed to be working.
Now that I opened the console at least once,
If I closeed the console and then reloaded the page, the onload was firing.
If I typed the URL and then pressed enter, the onload was firing.
It took me a couple of days to actually figure out what I was doing wrong.
The issue was with the console.log statements. At a lot of places in my code, I had done a lot of console logging. Even one of the plugins that I was using - jplayer has a an uncommented console message somewhere in the code.
The issue was that, unless you open the console at least once in IE, the console object is not available. Which means that the code will fail at the first console.log that it encounters.
Now, I was in no mood to comment out all my console.log statements just for the sake of testing it in IE. So, this is what I did instead. Right at the top of my document.ready jquery function, I wrote this small snippet of code.
if(!window.console){
console={};
console.log = function(){};
}
What it basically does is creates a dummy console.log function placeholder so that the code can run in IE but it will work only as long as console.log is the only console function that you are making use of in your code or in your plugins.
Just my 2 cents. Been pulling my hair over this issue for longer than I care to admit. I hope this is useful to at least someone.
You need to figure out if the code doesn't run at all, I.e. never enters your function, or if it fails on some specific line inside your function. Does IE9 show any warnings or js errors?
The easiest thing to do is stick a bunch of alert() statements in the code to see where it stops and narrow down to that line.
If it never enters your function then you need to look higher, where the call is being made.
Just a small note; When you use any debugging keywords (like console.log) or anything related, IE9 will escape this JS function if and only if the debugger is not on (with F12)
Actually I don't know what else cause a problem, but for me, my problem was the word "console.log" while debugger not on in IE9 ... I know this is already an answered question, but I felt it needs to be be known.
Okay, I figured it out. It has to do with some weird way IE handles IF statements.
In my init function I had two IF statements, one which checked if a variable existed and then logged the value of that variable. The other which checked to see if the value of the same variable was equal to an arbitrary string.
After removing the first IF statement, everything seems to work properly. I also decided to use a different onload function which can be seen below:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, true);
} else if (document.all && !window.opera){ //Crude test for IE
//Define a "blank" external JavaScript tag
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag=document.getElementById("contentloadtag");
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete") {
init();
//ie('open');
}
}
}
Related
I have built my own javascript console in a website! Pressing the GO - Button runs the following function, after comments are removed from the code:
var interv;
function go(code) {
code += "clearInterval(interv);";
interv = setInterval(code,1);
}
My problem appears when calling very time-consuming functions or when there's a mistake in the code: it doesn't stop, sometimes even the browser crashes.
What have I done wrong? Or is there a better way to get the same result?
Here's a JSFiddle (it works best in Firefox)
PS: Maybe you like the spirograph function in this jsFiddle. It's similar to a function in this website, but better.
I have some JavaScript functions like this:
function onSelectRow_${itemid}(){
something;
}
This it is appearing like this in Firebug script tab:
function onSelectRow_87878(){
something;
}
I put multiple break points (it has more than 20 lines, I put one in for example) in Firebug -> Script tab.
But the problem is, Firebug is not able to do debug these methods, ie. it is not stopping execution it executing as usual. I tried multiple times.
This is my actual code and use:
function onSelectRow_${escapedId }(rowId){
}
<jqgrid:grid onSelectRow="onSelectDeviceRow_${escapedId }"
What can I try to resolve it?
You can use debugger
function onSelectRow_87878()
{
debugger; //add here
something;
}
When you open Firebug, enable Script,and it will automatically go to the debugger point
debugging in firefox
I'm currently working with a large pre-existing codebase that may have one or more setInterval timers running all the time, from various plug-ins or libraries. This basically makes it impossible to try to use Break on Next to debug what happens when I click on an element.
Problem: As soon as I click Break on Next, the browser debugger (tried with Firebug and Chrome) stops in one of the setInterval functions before I have a chance to interact with the page to really debug the event that I want.
Specific problem: I have checkboxes that stay unchecked when unchecked, no matter how many times I click on them. I've removed the ID and class names as well to no avail and appear to have no event handlers attached.
Note: not using jQuery
This may brake other things, but what if you try to monkey-patch-out those calls like this:
window.setInterval = function() { console.log("setInterval", arguments); };
window.setTimeout = function() { console.log("setTimeout", arguments); };
If you find that some of timeouts/intervals are actually needed to reproduce your problem, you could try letting them through. Than the code could be something like:
window.oldSetTimeout = window.setTimeout;
window.setTimeout = function() {
if (arguments[0] == "code you want to allow") {
oldSetTimeout.apply(null, arguments);
} else {
console.log("setTimeout", arguments);
}
};
Note: I wouldn't be suprised it monkey-patching setTimeout does not work cross-browser, but it works on FF 18.0
I have this script on a page of mine and the setTimeout function never fires. It's just an alert right now but i'm just testing it out. I'm doing a meta refresh on the page just after it if that's any clue, but i've also given that a 10 sec delay so the page isn't refreshed before it's supposed to trigger.
Also, the related question: If I run a javascript with a delay of, say, 10 seconds (with setTimeout) and in that javascript I try to modify a design element that's not on the page when the setTimeout is declared but will be by the time the script is fired. Will it work?
<script language=javascript>
var xmlhttp_get_memento;
function loop_alerte(){
setTimeout( function() {
alert("timeout");
}, 5000);
xmlhttp_get_memento = new XMLHttpRequest();
if (xmlhttp_get_memento==null)
{
alert ("Browser does not support HTTP Request (1)");
return;
}
var url="crm/ajax/get_mementos.php";
url=url+"?sid="+Math.random();
xmlhttp_get_memento.onreadystatechange=function() {
if (xmlhttp_get_memento.readyState == 4) {
alert(xmlhttp_get_memento.responseText);
schimbare_tip_cursor("default");
}
else{
schimbare_tip_cursor("progress");
}
};
xmlhttp_get_memento.open("GET",url,true);
xmlhttp_get_memento.send(null);
}
loop_alerte();
</script>';
Your setTimeout looks good, so there's probably something else that's wrong. Have you tried using a javascript debugger to see if you get any errors?
As for your second question, yes, that shouldn't be any problem, as the anonymous function inside the setTimout won't be evaluated until it runs. Live sample here: http://jsbin.com/afonup/2/edit Both with and without jQuery.
There is nothing wrong with your setTimeout, you will need to debug further
As for your second question -- the function will run, but whatever it is you were trying to do will not work.
Cleaning up your code would be a nice start. I can imagine a browser doesn't understand the tag <script language=javascript>. I suggest to use <script type="text/javascript"> and if you're lucky, your javascript might work!
[Edit: I'm replacing the original, confusing question with a simplified example demonstrating the problem.]
Background
I'm trying to write a userscript which will run in Chrome. This script needs to call a JavaScript function AlertMe() that is outside of the userscript -- this function is part of the page and contains variables that are generated dynamically on the server-side, so it isn't possible to re-write this function in my userscript.
Code
Script on the page (visit the page):
<script type="text/javascript">
function AlertMe()
{
alert("Function AlertMe was called!");
// then do stuff with strings that were dynamically generated
// on the server so that I can't easily rewrite this into the userscript
}
</script>
My userscript (install it in Chrome):
function tryAlert()
{
if (typeof AlertMe == "undefined") {
console.log('AlertMe is undefined.');
window.setTimeout(tryAlert, 100);
}
else {
AlertMe();
}
}
tryAlert();
The Problem
When I tried to simply call the function, Chrome's console let me know that AlertMe is not defined. Thinking that this was because my userscript was running before all other scripts had been loaded, I used setTimeout to wait for the AlertMe function to become defined.
Unfortunately, if you install the script then visit the page, you'll see that this just outputs AlertMe is undefined. forever and never calls the function. If you type typeof AlertMe into Chrome's console, it will correctly respond with "function", so why is it that my userscript always thinks that AlertMe is undefined?
You can always write a little function that checks to see if the function is loaded
function waitForFnc(){
if(typeof absearch == "undefined"){
window.setTimeout(waitForFnc,50);
}
else{
runMyFunction();
}
}
function runMyFunction(){
var urlParams = window.location.search.substring(1).split('&'),
username = "",
hscEmailInput = document.getElementById('userfield6'),
i = 0;
if (urlParams !== "") {
for (i = 0; i < urlParams.length; i++) {
if (urlParams[i].substr(0,4) === "USER") {
username = urlParams[i].replace('USER=', '');
hscEmailInput.value = username + '#example.com';
absearch('&PAGESIZE=1');
}
}
}
}
waitForFnc();
This is not a matter of timing.
You're bumping into Greasemonkey's security restrictions, which prevent you from executing functions in the page. Please see my answer to this previous question for an explanation and some safe workarounds:
UserScripts & Greasemonkey: calling a website's JavaScript functions
If the problem is indeed that your script runs too early, perhaps checking and waiting until the DOM is ready is the solution: Relying on DOM readiness to invoke a function (instead of window.onload)
Edit
This answer on SO might also prove to be useful.