IE8 problem with javascript function that calls itself in setTimeout - javascript

i have a locate function defined in javascript
var locID;
function locateMe()
{
if(locID > 0)
{
// i do a jquery post here
}
setTimeout(locateMe, 2000);
}
// my document ready function is here, and inside it, at the end of it
// i do this
locID = 0;
locateMe();
when i test this code in firefox, the locateMe function is called every two seconds and works as expected. when i test the code in IE8 the function is never called (at least it appears to never be called from what i can see using IE's developer tools)
note: there is code defined in a click event handler for the 'zone_row' class that modifies locID. again, in firefox everything works as expected. the strange thing is, in IE when a zone_row is clicked the function WILL be called ONCE. i can see that both on the developer tools and through the result of the action of that jquery post.
i figured there is just some anomly with IE that i am not familiar with yet. what am i doing wrong?
EDIT: changed "locateMe();" to locateMe inside the setTimeout call.
UPDATE: adding more of my code (per request in comments) to show placement (albeit not much more code than my first post).
<script type="text/javascript">
var z_items;
var locID;
function locateMe()
{
if(locID > 0)
{
// my jquery post is here
}
setTimeout(locateMe, 2000);
}
$(document).ready(function()
{
// ... some click events and get requests here ...
locID = 0;
locateMe();
});
</script>
i also tried wrapping the call in a setTimeout (no effect) and changing the DOCTYPE (this actually caused IE to never call the function as opposed to now where it calls it ONCE and never again).

problem solved. i found an answer to another problem i was having from this post:
Prevent browser caching of jQuery AJAX call result
upon adding $.ajaxSetup({ cache: false }); to my document ready function, it solved THIS problem too. it looks like all this time it was a caching issue.

I've found that for IE (even IE9) that if you nest the self-called function in an anonymous function it works. But it does look like Toddeman's problem was related to the ajax part.
So the code would be:
function locateMe()
{
/* ... */
//IE way (still works in Chrome and FF):
setTimeout(function () { locateMe(); }, 2000);
//original: setTimeout(locateMe, 2000);
}

Use
setTimeout( locateMe, 2000 );

Related

how to "kill" or cancel setTimeout function

How can I "kill" this setTimout function but not to break my code?
I tried with clear and it didn't work.
For some reason when I delete it everywhere it breaks my code (also if i remove this function evertwhere).
When I say "return" on the top before timeout executes my jQuery shows up but my code doesn't work.
To mention also my jQuery file loads in Mozilla. It also loads on my local machine in Chrome and Safari, but not in live on the server( im also using Wordpress) Safari/Chrome.
Function with the setTimeout
function queueRender() {
var _this = this;
settings.queueRenderTimeout = setTimeout(function(){
render();
}, settings.debounce);
if(typeof settings.queueRenderTimeout !== "undefined") {
clearTimeout(settings.queueRenderTimeout)
}
render();
}
Here is render function
function render() {
element.find(">").remove();
var t = templates.quiz(quiz);
element.append(t);
$(settings.append).append(element);
}
-- so in this case, my jQuery loads, but my quiz breaks.
if i change the order and put first IF statement then my code doesnt break.
Here is my settings:
var defaults = {
append: "body",
quiz_template: "#quiz_template",
question_template: "#question_template",
answer_template: "#answer_template",
result_template: "#result_template",
shuffle: true
// debounce: 10
}
Code is something working sometimes don't. It works on my local machine, but not on the server. I feel like there is still some delay from the setTimout even when I leave it "undefined".

Is having 100 document ready better or worse than 1 document ready?

Just wondering if the amount of document.ready calls affects page load speed.
Is there a way in Gulp / Grunt to uglify / minify JS by removing seperate document ready functions?
Just check it!
I don't see significant difference in Chrome.
As I know, it was critical for IE8, but didn't check this fact.
IE11 shows 2 seconds on the first snippet, when the others take 200 ms only.
Also, seems like jQuery already aggregates load events.
Don't forget
When you are running same code in one tab, browser remembers something and runs it faster.
Reload the page is not enought. Open a new tab instead.
After opening a new tab, run snippets in different order.
If the snippet is ran first on the tab, it will get additional slowdown, comparing the other three.
for (var q=0; q<1000; ++q) {
document.addEventListener('DOMContentLoaded', (function (i) {
console.log(i);
}).bind(null, q));
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('output').textContent = performance.now().toFixed(3);
});
<output></output>
document.addEventListener('DOMContentLoaded', function () {
for (var q=0; q<1000; ++q) {
(function (i) {
console.log(i)
}).bind(null, q)();
document.querySelector('output').textContent = performance.now().toFixed(3);
}
});
<output></output>
for (var q=0; q<1000; ++q) {
$((function (i) {
console.log(i);
}).bind(null, q));
}
$(function () {
document.querySelector('output').textContent = performance.now().toFixed(3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<output></output>
$(function () {
for (var q=0; q<1000; ++q) {
(function (i) {
console.log(i)
}).bind(null, q)();
document.querySelector('output').textContent = performance.now().toFixed(3);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<output></output>
Maybe it's just me as a JavaScript avoider, but none of the scripts have document.ready inside. If you JS guys talk about document.ready, that's a synonym for addEventListener('DOMContentLoaded')?
There are two events: DOMContentLoaded and load (window.onload). First of them occures when the body pasring is complete, but some assets are loading still. The second - when the page is completely loaded. First one is nice for running scripts with dom manipulations, but browsers not always had support of it.
So jQuery uses the first of these two events and classic form of subscription was
$(document).ready(function () {
// ...
});
but after some versions if was simplified to passing function directly into jQuery:
$(function () {
// ...
});
So in vanilla examples I'm using the first of 2 events, and in jQuery examples I'm using the short form of subscription on it. As browsers without support of this event are very old it's correct to assume that jQuery always uses DOMContentLoaded (probably the load way is removed in version 2 - didn't check it, but see no reasons to keep it there).
Many document ready calls shouldn't affect much the application performance. The best solution may be having only one and init there all you need. But it depends on your application structure and you should be more confortable having more than one. Anyway, I don't think there is any Gulp task that wraps different ready functions in one, because it will touch the application logic.
You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal.
It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block.
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
});
output was
hello1
something
hello2
Check this post and this one
Yes, you can use multiple document ready handler, there is no special advantage even though you can use jQuery code in several place. You can’t use the variable inside one in another since those are in different scope.
Actually jQuery event handler pushing function for execution in
queue of a particular event. When event is fired all functions
executes one by one from particular events row/stack/queue based on
return value of parent sequential function.
BUT
There is one thing to note that each $(document).ready() function call
must return. If an exception is thrown in one, subsequent calls will
never be run.
$(document).ready(function() {
document.write('<h3>In First ready function</h3>');
var foo = function() {
console.log('inside foo');
}
document.write("foo:" +(typeof foo)+"<br>");
document.write("bar:" +(typeof bar)+"<br>");
});
$(document).ready(function() {
document.write('<h3>In Second ready function</h3>');
var bar=function bar() {
console.log('inside bar');
}
document.write("foo:" +(typeof foo)+"<br>");
document.write("bar:" +(typeof bar)+"<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Actually jQuery $(document).ready() method is attach function with DOMContentLoaded event using addEventListener method.
Yes you can have multiple instance of it on a single page. There is no particular advantage. All will get executed on first called first run basis.

Business catalyst prototype-core.ashx Refused to set unsafe header "Connection" conflicts

I currently use Adobe Business Catalyst on an ecommerce site and it run into the same problem:
When clicking add to cart the log shows:
prototype-core.ashx Refused to set unsafe header "Connection"
all custom javascript I have and jQuery breaks and does not ready some functions.
I tried using methos such as jQuery noConflicts();
var j = jQuery.noConflict();
Still nothing works well, I cant provide a sample code because everything is working from the server and I use another method to have a work around it for the time being.
Any suggestions please advise.
If you have a look into the prototype-core.ashx you will find this
if(!MS.Browser.isIE) {
this.xmlHttp.setRequestHeader("Connection", "close") // Mozilla Bug #246651
}
This is not an issue, it is just a line of code your browser does not understand, if you use Mozilla you will not see this error in your console, but you will see a bunch of different warnings.
There is quite a lot on Stackoverflow about the issue that JavaScript doesn't work after an Ajax call.
What you can do to fix it is call all your functions again after the add to cart button has been pressed.
So first I have my JavaScript functions FirstFunction(); SecondFunction(); ThirdFunction(); and then I call them like this
function FirstFunction() {
//do whatever you want to do
}
function SecondFunction() {
//do whatever you want to do
}
function ThirdFunction() {
//do whatever you want to do
}
$(document).ready(function () {
// do it once onload
FirstFunction();
SecondFunction();
ThirdFunction();
$('.main_content').on('click',function() {
// do it again onclick
FirstFunction();
SecondFunction();
ThirdFunction();
});
});
This way all your functions are loaded again when you click on inside .main_content.

IE11 script onload not working (sometimes)

I am currently working on a data-intensive web application that frequently communicates with an external API and retrieves JSONP data when returned. The script depends upon a library called head.js v1.0.3. http://headjs.com/ to accomplish this. However, I noticed that in IE 11 for some reason, the onload event for the script sometimes, but not always, fires before the script has actually loaded into the browser. The behavior is demonstrable whether using head.js or not. Alternatively, I may create a script element with the onload event set to capture the returned data. Sometimes it works, and sometimes not. Even more weird is that once it happens the first time, it seems to keep happening for the duration of the browser session.
Any ideas for a workaround?
Here is some example code:
//somejson.js
/*
window["queryResult"] = {blah:'blah'}
*/
function loadScript() {
head.load("/somejson.js", afterScriptLoad)
}
function afterScriptLoad() {
var result = queryResult
//Throws error because window.queryResult is sometimes undefined
}
After a little bit of research, it seems the only way around this bug is to modify the API so that once the variable holding the JSONP is initialized, the script itself triggers the callback. Unfortunately, this would not work as a solution for others if they do not have access to modify whatever API is in use, but it does solve the problem for me.
//somejson.js
/*
window["queryResult"] = {blah:'blah'}; scriptCallback()
*/
function loadScript(callback) {
var c = new afterScriptLoad(callback)
window["scriptCallback"] = c
head.load("/somejson.js", c)
}
function afterScriptLoad(callback) {
var retrieved = false
return function () {
if (!retrieved) {
retrieved = true
callback(queryResult)
}
}
}
function myCallback(response) {
//do something
}

Ajax .load() won't work when triggered initially

So I have a simple tab system which I handle with the .load function to load the desired content. The problem is that the page itself which contains this tab system is a ajax loaded content. And for some reason the initial call of the tab function to display the initial tab content won't work. But after manually choosing a tab, the load function loads the content properly.
her some code to look at:
The tab handler:
function loadTab(tab) {
$(".tab_a:eq("+otab+")").removeClass("tab_slc");
$('#tab_content').hide();
$('#tab_content').load("include/tab_downloadVersions.html .tab:eq("+tab+")");
$(".tab_a:eq("+tab+")").addClass("tab_slc");
$('#tab_content').fadeIn(function() {});
otab = tab;
}
at the end I call loadTab(tab); and the thing should be initialized. but for some reason the content remains empty. As soon as you manually click on a tab (I have an on click function which calls loadTab(tab) everything starts working)
Because the code by itself works, I think the problem is caused by the other script which handles the page itself. It is also a .load function which loads the page, which loads this tab system.
So do multiple .loads don't like each other? and if so, what can I change?
Thanks in advance ;)
EDIT: I could't post the entire code for some reason, but if you go here you can see the site in action with all the scripts:
n.ethz.ch/student/lukal/paint.net
The tab system is on the download page.
EDIT:-----------------------------------------------------------------------------------------------------------------------------
Big Update
So this is still the same issue but with a slight twist: I did what was recommended in the comments and put my secondary .load() call inside the success call of the first one.
$("#content").load("pages/contact #contentInside", function() {
$("#OtherContent").load("include/info #OtherContentInside");
});
So this works.
But now I had the great idea to make a giant load function. It is a slightly better function than just the plain load, cause it does some fading and stuff. But now I have the same problem, but even more complicated. I created the load function as a "plugin" so the function itself is in a different script file and therefore I can't access the inside of the success function. I solved this problem with a return $.ajax(); and a .done() call. The problem here is that there is some rare case where it just skips the secondary load function. So I am searching for a guaranteed way of controlling the order of the .load calls. Any idea?
The mock-up website is up to date with the new scripts if you wish to take a look. And people were complaining about potential virus spread from my link. For some reason I can't post long code snippets so the site is the best source I got to show everything. If you know a more trustworthy way to share my code please let me know.
We cannot see the rest of your code to tell where the initial call is being invoked from. A set up like the following should work:
$(function() {
var tab = 0;
loadTab( tab );
});
function loadTab(tab) {
//WHAT IS otab???
$(".tab_a:eq("+otab+")").removeClass("tab_slc"); //<<<==== otab
$('#tab_content').hide();
$('#tab_content').load("include/tab_downloadVersions.html .tab:eq("+tab+")");
$(".tab_a:eq("+tab+")").addClass("tab_slc");
$('#tab_content').fadeIn(function() {});
otab = tab;
}
Update
The reason it does not work initial is because otab is not defined the first time the function is called. You have initialized otab at the end of the function but you are using it at the beginning of the function.
UPDATE 2
I have had a chance to look at your code and I just found out what the issues are:
You do not have DOM ready
You are not calling the function on page load.
The following version of your code should work -- try not to use global variable as you're doing with otab. Since you're loading this script at the end of the page (an you are using event delegation) you may get away with DOM ready. Adding .trigger('click') or click() as indicated below should resolve the issue.
//Tab-loader
//Haeri Studios
var tab = 0;
var otab = tab;
var counter = 0;
//click detect
$(document).on('click', '.tab_a', function() {
tab = counter == 0 ? tab : ($(this).attr('id'));
loadTab(tab);
counter++;
return false;
})
.trigger('click'); //<<<<<===== This will call the function when the page loads
//Tab setup
function loadTab(tab) {
//Content Setup
$(".tab_a:eq("+otab+")").removeClass("tab_slc");
$('#tab_content').hide();
$('#tab_content').load("include/tab_downloadVersions.html .tab:eq("+tab+")");
$(".tab_a:eq("+tab+")").addClass("tab_slc");
$('#tab_content').fadeIn(function() {});
otab = tab;
}
//Initialize << WHAT ARE YOUR INTENTIONS HERE .. DO YOU REALLY NEED THIS PIECE?
$.ajax({success: function() {
loadTab(tab);
}});
A partial answer to this problem was to call the loadTab function inside the success call of the page load function, like charlietfl pointed out. But the problem is that there is no need to call the tabloader every time a new page gets called. So I would rather not have a rare call in every page setup function.
I am a bit disappointed by the system on stackoverflow. It seems like if you have not a high reputation level, no one gives a "S" about your questions. Well but at least some input was give, for which I am very thankful.
So by digging deeper into google I found out that the callback can be manually placed in the function where ever you like.
so if we have a function:
foo(lol, function() {
//This after
});
this does stuff after foo() is done. But what if we have another function inside foo() which we also need to wait for:
function foo(lol) {
bar(troll, function() {
//This first
});
}
The bar function is not relevant to the success call of foo. This causes the unpredictable outcome of calls.
The trick is to control when the success function of foo gets called.
If we add a parameter(callback) inside foo and call this "parameter" (callback();) inside the success call of bar, we can make sure the order is guaranteed.
And that's it:
function foo(lol, callback) {
bar(troll, function() {
//This first
callback(); //<-This callback placement defines when it should be triggered
});
}
foo(lol, function() {
//This after
});
We get:
//this first
//this after

Categories

Resources