原生javascript实现异步的7种方式

原生的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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章