原生的javascript 實現異步的方式其實遠遠不至7種,
大可以分3類,
延遲類型:setTimeout(setInterval也是可以的)、requestAnimationFrame、setImmediate(IE10及以上)
監聽事件實現的類型:監聽new Image加載狀態、監聽script加載狀態、監聽iframe加載狀態、Message
帶有異步功能類型 Promise、ajax( XMLHttpRequest、ActiveXObject)、Worker;
考慮到
1.iframe 效率過慢;
2.ajax 在ie下一定要加載真實的文件才能觸發open及send;
3.Worker 雖然具有異步特性,但它屬於多線程的範疇,需要將主要的算法寫在單獨的js文件中才能完整體現其優點,若單單爲了異步化而使用的話太浪費了。
所有這3種方式就不列出。
一、實現異步的方式
1.setTimeout
2.setImmediate
3.requestAnimationFrame
4.監聽new Image加載狀態
5.監聽script加載狀態
6.Message
7.Promise
setTimeout
這個是最簡單的
setTimeout( function() {
console.log(1);
});
console.log(2);
setImmediate
IE10添加的新功能,專門用於解放ui線程。IE10以下及其他瀏覽器不支持
setImmediate(function(){
console.log(1);
});
console.log(2);
requestAnimationFrame
HTML5/CSS3時代新產物,專門用於動畫。低級瀏覽器不支持
var asynByAniFrame = (function(){
var _window = window,
frame = _window.requestAnimationFrame
|| _window.webkitRequestAnimationFrame
|| _window.mozRequestAnimationFrame
|| _window.oRequestAnimationFrame
|| _window.msRequestAnimationFrame;
return function( callback ) { frame( callback ) };
})();
asynByAniFrame(function(){
console.log(1);
})
console.log(2);
監聽new Image加載狀態實現
通過加載一個data:image數據格式的圖片,並監聽器加載狀態實現異步。
儘管部分瀏覽器不支持data:image圖片數據格式,但仍然可以觸發其onerror狀態實現異步,但IE8及以下對data:image數據格式的圖片,onerror爲同步執行
function asynByImg( callback ) {
var img = new Image();
img.onload = img.onerror = img.onreadystatechange = function() {
img = img.onload = img.onerror = img.onreadystatechange = null;
callback();
}
img.src = "data:image/png,";
}
asynByImg(function(){
console.log(1);
});
console.log(2);
監聽script加載狀態實現
原理同new Image是一樣的,生成一個data:text/javascript的script,並監聽其加載狀態實現異步。
儘管部分瀏覽器不支持data:text/javascript格式數據的script,但仍然可以觸發其onerror、onreadystatechange事件實現異步。
var asynByScript = (function() {
var _document = document,
_body = _document.body,
_src = "data:text/javascript,",
//異步隊列
queue = [];
return function( callback ) {
var script = _document.createElement("script");
script.src = _src;
//添加到隊列
queue[ queue.length ] = callback;
script.onload = script.onerror = script.onreadystatechange = function () {
script.onload = script.onerror = script.onreadystatechange = null;
_body.removeChild( script );
script = null;
//執行並刪除隊列中的第一個
queue.shift()();
};
_body.appendChild( script );
}
})();
asynByScript( function() {
console.log(1);
} );
console.log(2);
Message
html5新技能,通過監聽window.onmessage事件實現,然後postMessage發送消息,觸發onmessage事件實現異步
var asynByMessage = (function() {
//異步隊列
var queue = [];
window.addEventListener('message', function (e) {
//只響應asynByMessage的召喚
if ( e.data === 'asynByMessage' ) {
e.stopPropagation();
if ( queue.length ) {
//執行並刪除隊列中的第一個
queue.shift()();
}
}
}, true);
return function( callback ) {
//添加到隊列
queue[ queue.length ] = callback;
window.postMessage('asynByMessage', '*');
};
})();
asynByMessage(function() {
console.log(1);
});
console.log(2);
Promise
ES6的新技能,具有異步性質
var asynByPromise = (function() {
var promise = Promise.resolve({
then : function( callback ) {
callback();
}
});
return function( callback ) {
promise.then(function(){
callback();
})
};
})();
asynByPromise(function() {
console.log(1);
});
console.log(2);
二、各種異步方式的運行效率
測試代碼
/**
* 檢驗一個方法是否瀏覽器原生
* @param { Function } func 需檢測的方法
* @return { Boolean } 是否瀏覽器原生
*/
function isNativeFunc( func ) {
return typeof func === 'function' && /^[^{]+\{\s*\[native \w/.test( func );
}
var _window = window,
frame = _window.requestAnimationFrame
|| _window.webkitRequestAnimationFrame
|| _window.mozRequestAnimationFrame
|| _window.oRequestAnimationFrame
|| _window.msRequestAnimationFrame;
_window = null;
var asynByPromise = isNativeFunc( window.Promise ) && (function() {
var promise = Promise.resolve({
then : function( callback ) {
callback();
}
});
return function( callback ) {
promise.then(function(){
callback();
})
};
})();
var asynByAniFrame = isNativeFunc( frame ) && function( callback ) {
frame( callback );
};
var asynByWorker = (function() {
//生成一個新線程
var worker = new Worker('asynWorker.js'),
queue = [];
//監聽線程
worker.addEventListener('message', function (e) {
//處理結果
queue.shift()();
}, true);
return function( callback ) {
queue[ queue.length ] = callback;
worker.postMessage('');
};
})();
var asynByMessage = isNativeFunc( window.postMessage ) && (function() {
//異步隊列
var queue = [];
window.addEventListener('message', function (e) {
//只響應asynByMessage的召喚
if ( e.data === 'asynByMessage' ) {
e.stopPropagation();
if ( queue.length ) {
//執行並刪除隊列中的第一個
queue.shift()();
}
}
}, true);
return function( callback ) {
//添加到隊列
queue[ queue.length ] = callback;
window.postMessage('asynByMessage', '*');
};
})();
function asynByImg( callback ) {
var img = new Image();
img.onload = img.onerror = img.onreadystatechange = function() {
img = img.onload = img.onerror = img.onreadystatechange = null;
callback();
}
img.src = "data:image/png,";
}
//是否支持圖片異步方式
var supAsynImg = true;
asynByImg(function(){
//IE8及以下對data:image數據格式的圖片,onerror爲同步執行
supAsynImg = false;
})
var asynByScript = (function() {
var _document = document,
_body = _document.body,
_src = "data:text/javascript,",
//異步隊列
queue = [];
return function( callback ) {
var script = _document.createElement("script");
script.src = _src;
//添加到隊列
queue[ queue.length ] = callback;
script.onload = script.onerror = script.onreadystatechange = function () {
script.onload = script.onerror = script.onreadystatechange = null;
_body.removeChild( script );
script = null;
//執行並刪除隊列中的第一個
queue.shift()();
};
_body.appendChild( script );
}
})();
function asynBySetImmediate( callback ) {
setImmediate( callback );
}
setTimeout(function() {
console.log('setTimeout');
});
if ( supAsynImg ) {
asynByImg(function() {
console.log('asynByImg');
});
}
asynByScript(function() {
console.log('asynByScript');
});
if ( isNativeFunc( window.setImmediate) ) {
asynBySetImmediate(function() {
console.log('asynBySetImmediate');
});
}
if (isNativeFunc( window.Promise )) {
asynByPromise(function() {
console.log('asynByPromise');
});
}
if ( isNativeFunc( frame ) ) {
asynByAniFrame(function() {
console.log('asynByAniFrame');
});
}
if ( isNativeFunc( window.postMessage ) ) {
asynByMessage(function() {
console.log('asynByMessage');
});
}
asynByWorker(function() {
console.log('asynByWorker');
});
按照這樣的結果,其實留下4個就夠了
高級瀏覽器
支持promise的時候 asynByPromise 最快
支持requestAnimationFrame的時候 比 promise 慢,比其他快
其他瀏覽器
支持data:image數據格式圖片異步的,asynByImg 比 asynScript快
每個瀏覽器都支持 data:text/javascript 數據格式的異步方式
所以
asynByPromise > asynByAniFrame > asynByImg > asynByScript
奇怪的是,IE中 setImmediate 從來沒跑贏過 setTimeout。
三、最終代碼
/**
* 檢驗一個方法是否瀏覽器原生
* @param { Function } func 需檢測的方法
* @return { Boolean } 是否瀏覽器原生
*/
function isNativeFunc( func ) {
return typeof func === 'function' && /^[^{]+\{\s*\[native \w/.test( func );
}
var _window = window,
frame = _window.requestAnimationFrame
|| _window.webkitRequestAnimationFrame
|| _window.mozRequestAnimationFrame
|| _window.oRequestAnimationFrame
|| _window.msRequestAnimationFrame,
//是否支持圖片異步方式
supAsynImg = true;
_window = null;
function asynByImg( callback ) {
var img = new Image();
img.onload = img.onerror = img.onreadystatechange = function() {
img = img.onload = img.onerror = img.onreadystatechange = null;
callback();
}
img.src = "data:image/png,";
}
asynByImg(function(){
//IE8及以下對data:image數據格式的圖片,onerror爲同步執行
supAsynImg = false;
});
var asynFire =
//瀏覽器中有Promise方法且爲原生
isNativeFunc( window.Promise )
&&
(function() {
var promise = Promise.resolve({
then : function( callback ) {
callback();
}
});
return function( callback ) {
promise.then(function(){
callback();
})
};
})()
||
//瀏覽器中有requestAnimationFrame方法且爲原生
isNativeFunc( frame )
&&
function( callback ) {
frame( callback );
}
||
//支持圖片異步
supAsynImg
&&
asynByImg
||
//script異步
(function() {
var _document = document,
_body = _document.body,
_src = "data:text/javascript,",
//異步隊列
queue = [];
return function( callback ) {
var script = _document.createElement("script");
script.src = _src;
//添加到隊列
queue[ queue.length ] = callback;
script.onload = script.onerror = script.onreadystatechange = function () {
script.onload = script.onerror = script.onreadystatechange = null;
_body.removeChild( script );
script = null;
//執行並刪除隊列中的第一個
queue.shift()();
};
_body.appendChild( script );
}
})();
if ( asynFire !== asynByImg ) {
asynByImg = null;
}