起因
在阅读layUI的源代码关于加载远程脚本的代码中出现了判断当前js脚本地址的代码,其中出现了对于document.currentScript支持与不支持时,会走不同的逻辑。
如果支持document.currentScript,直接从document.currentScript.src获取当前脚本运行的地址;
如果不支持document.currentScript,则遍历文档所有的<script>标签,判断哪个<script>标签的readyState为'interactive',则说明此标签的src属性为当前脚本运行的地址。
代码
//获取layui所在目录
getPath = function () {
var jsPath = doc.currentScript ? doc.currentScript.src : function () {
var js = doc.scripts
, last = js.length - 1
, src;
for (var i = last;i > 0;i--) {
if (js[i].readyState === 'interactive') {
src = js[i].src;
break;
}
}
return src || js[last].src;
}();
return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
}()
为什么要进行这种判断?
首先让我们看一下Document.currentScript的浏览器支持情况,具体如下图:
由图可见IE浏览器在Document.currentScript的支持上全线阵亡,那在IE浏览器上如何获取当前脚本的地址呢?原来IE的<script>标签对象支持一个readyState的属性,其属性值与Document.readyState一样,loading表示正在加载,interactive表示当前处于互动状态(也就是正在运行),complete表示脚本已经加载完成。我们可以利用readyState是否为interactive来判断某个<script>标签为当前运行代码所在的位置。
需要的注意的是HTMLScriptElement.prototype.readyState只有IE支持,Chrome和Firefox均不支持。
根据上述原理,对于Document.currentScript的polyfill实现,其实就是基于HTMLScriptElement.prototype.readyState来实现的,具体可阅读https://github.com/JamesMGreene/document.currentScript/blob/master/dist/document.currentScript.js 的具体实现。
相关文档
Document.currentScript: developer.mozilla.org/en-US/docs/… Document.readyState: developer.mozilla.org/en-US/docs/…