多个相同script引用探索

时间:2023-03-09 17:01:17
多个相同script引用探索

1、页面直接就有,或者document.write页面加载同步输出

其实就是当script是页面初始加载的一部分的情况,script是同步的,只有在上一个加载并执行完才会进行下一个script加载。
当然,可手动设置异步:async="async",页面加完,循序依次执行

<script src="http://localhost:8083/-0test/test.js?1"></script>
<script src="http://localhost:8083/-0test/test.js?2"></script>
<script src="http://localhost:8083/-0test/test.js?3"></script>
<script src="http://localhost:8083/-0test/test.js?4"></script>
<script src="http://localhost:8083/-0test/test.js?5"></script>
<script src="http://localhost:8083/-0test/test.js?6"></script>

2、页面中只有js增加的script,或是说是页面加载好后再js增加script

js全部执行完后,并且script已全部成功添加,新增的script才会执行,并且依次顺序执行。
所有ie也是如此

html文件

<div id="info"></div>
<script>
var s = document.createElement('script');
s.src = 'http://localhost:8083/-0test/test.js?5';
document.body.appendChild(s);
var s = document.createElement('script');
s.src = 'http://localhost:8083/-0test/test.js?6';
document.body.appendChild(s);
</script>

test.js文件

var s = document.getElementsByTagName('script');

s = s[s.length - 1];

document.getElementById('info').innerHTML +='<p>'+ s.src;

输出

http://localhost:8083/-0test/test.js?6
http://localhost:8083/-0test/test.js?6

3、js同时增加多个script,页面中已存在其它script

这种情况比较复杂,而且一般不会发生

只有在所有页面中的script加载并执行完后,新增的script才会执行,并且依次顺序执行。
但,确实是在?2位置被增加的,也就是说,document.body.appendChild并没有什么特殊情况,依然与文档加载同步进行,加载到哪里便在哪处理。

ie全系列(此时最高为11)中有些无规律,也许是appendChild先执行,也许是文档中存在的先执行,但肯定是?2之后。

html文件

<div id="info"></div>
<script src="http://localhost:8083/-0test/test.js?1"></script>
<script src="http://localhost:8083/-0test/test.js?2"></script>
<p>一点内容</p>
<script>
var s = document.createElement('script');
s.src = 'http://localhost:8083/-0test/test.js?5';
document.body.appendChild(s);
var s = document.createElement('script');
s.src = 'http://localhost:8083/-0test/test.js?6';
document.body.appendChild(s);
</script>
<script src="http://localhost:8083/-0test/test.js?3"></script>
<script src="http://localhost:8083/-0test/test.js?4"></script>
<script src="http://localhost:8083/-0test/test.js?7"></script>
<p>一点内容2</p>

test.js文件 同上

输出

http://localhost:8083/-0test/test.js?1
http://localhost:8083/-0test/test.js?2
一点内容
http://localhost:8083/-0test/test.js?3
http://localhost:8083/-0test/test.js?4
http://localhost:8083/-0test/test.js?7
一点内容2
http://localhost:8083/-0test/test.js?7
http://localhost:8083/-0test/test.js?7