I have the following function in a much larger script that loads translations from a php file:
function loadLanguages(language){
var data = new Object();
data.language = language;
var dataString = $.toJSON(data);
var langSt = $.ajax({
url: "/VID/ajax/loadtranslations.php",
data: ({data: dataString}),
async: fal开发者_运维问答se
}).responseText;
var languageArr = $.evalJSON(langSt);
return languageArr;
}
Works in FF, but in IE7 and IE8 the browser will hang.. When I comment out the ajax call in the function IE doesn't hang. If I set it to async: true the function doesn't work anymore, but the browsers will not hang. Only if I set async to false, IE will hang. I'm a bit puzzled why!
You should never use async: false
; it will always hang the browser until the request finishes.
This is a necessary consequence of the fact that Javascript is single-threaded, and will never change.
Edit Sorry, you really meant hang (what you said); I and others just happily read block instead.
I notice you're using the responseText
of the XMLHttpRequest
object returned by $.ajax
directly. I think even with a synchronous request, I'd still use the callback:
function loadLanguages(language){
var data = new Object();
data.language = language;
var dataString = $.toJSON(data);
var languageArr = /* ...some appropriate default value if the request fails... */;
$.ajax({
url: "/VID/ajax/loadtranslations.php",
data: ({data: dataString}),
async: false,
success: function(langSt) {
languageArr = $.evalJSON(langSt);
}
});
return languageArr;
}
Old Answer:
When you use a synchronous Ajax request, on many browsers (not just IE), the user interface becomes completely nonresponsive during the request. On IE, it's particularly bad because it's not just your page, but the entire browser process that ends up waiting — the user can't even go off and do something else in another tab.
This leads to a poor user experience, to put it mildly.
It happens because for the moment, JavaScript on web browsers is single-threaded, and in many browsers, that thread is the UI thread. Even in non-browser-based applications, tying up the UI thread for non-UI processing is not ideal.
So you want to avoid using synchronous ajax requests whenever possible, and it's almost always possible (probably even always possible). It involves some refactoring in your approach, having function "A" start something that is later completed by function "B" (the "success" callack on the ajax call), but doing that refactoring (and then using that mindset in your design in the future) makes for a much better user experience overall.
Until web workers are widely implemented, you need to use that single JavaScript thread sparingly and think in terms of events and callbacks. I've found that being forced to do that actually improves my code in the end and is changing my approach to other environments for the better.
精彩评论