Js异步回调java_浅谈js文件引用方式及其同步执行与异步执行

任何以appendChild(scriptNode) 的方式引入的js文件都是异步执行的 (scriptNode 需要插入document中,只创建节点和设置 src 是不会加载 js 文件的,这跟 img 的与加载不同 )

html文件中的

html文件中的

html文件中的

1、

//同步加载执行的代码

2、

//同步加载执行xx.js中的代码

3、

document.write('

4、

xx.js中有下面代码:

document.write('

document.write('

则xx.js和11.js、22.js 都是同步加载和执行的。

如果 xx.js 以插入方式异步加载,则 11.js 和 22.js 仍然是同步加载的(异步中的同步,即,这2个文件的加载是分先后次序的)

测试:在11中 alert, 22中 document.write() ,可以看到 22中写入语句被阻塞

5、

下面这种方式,xx.js会在appendChild执行之后异步加载执行

var script = document.createElement("script");

script.setAttribute("src","xx.js");

documenrt.getElementsByTagName("head")[0].appendChild(script);

一个加载 js 文件的 函数:

var loadJS = function(url,callback){

var head = document.getElementsByTagName('head')[0],

script = document.createElement('script');

script.src = url;

script.type = "text/javascript";

head.appendChild( script);

script.onload = script.onreadystatechange = function(){

//script 标签,IE 下有 onreadystatechange 事件, w3c 标准有 onload 事件

//这些 readyState 是针对IE8及以下的,W3C 标准因为script 标签没有这个 onreadystatechange 所以也不会有 this.readyState ,

// 好在文件加载不成功 onload 不会执行,(!this.readyState) 是针对 W3C标准的

if ((!this.readyState) || this.readyState == "complete" || this.readyState == "loaded" ){

callback();

}

else

{

alert("can not load the js file")

}

}

}

对于第4点的测试(其中插入 alert 很容易看到加载时阻塞的)

tryjs.html

onreadystatechange="console.log('outer js callback ',this.readyState,' IE');">

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值