这篇文章给大家分享的是有关javascript实现异步的方法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
javascript实现异步的方法:1、使用setTimeout方法;2、使用setImmediate 方法;3、使用requestAnimationFrame方法;4、监听new Image加载状态;5、监听script加载状态方法。
本教程操作环境:windows7系统、javascript1.8.5版,DELL G3电脑。
javascript实现异步的方法:
1、setTimeout:这个是最简单的
setTimeout( function() {
console.log(1);
});
console.log(2);
2、setImmediate :IE10添加的新功能,专门用于解放ui线程。IE10以下及其他浏览器不支持
setImmediate(function(){
console.log(1);
});
console.log(2);
3、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);
4、监听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);
5、监听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);
感谢各位的阅读!关于“javascript实现异步的方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。