原生javascript實現非同步7種方式

來源:互聯網
上載者:User

原生的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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.