在阅读layUI
的源代码关于加载远程脚本的代码中出现了判断当前js脚本地址的代码,其中出现了对于document.currentScript
支持与不支持时,会走不一样的逻辑。
若是支持document.currentScript
,直接从document.currentScript.src
获取当前脚本运行的地址;
若是不支持document.currentScript
,则遍历文档全部的<script>
标签,判断哪一个<script>
标签的readyState
为'interactive'
,则说明此标签的src
属性为当前脚本运行的地址。javascript
//获取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
的浏览器支持状况,具体以下图:java
由图可见IE浏览器在Document.currentScript
的支持上全线阵亡,那在IE浏览器上如何获取当前脚本的地址呢?原来IE的<script>
标签对象支持一个readyState
的属性,其属性值与Document.readyState
同样,loading
表示正在加载,interactive
表示当前处于互动状态(也就是正在运行),complete
表示脚本已经加载完成。咱们能够利用readyState
是否为interactive
来判断某个<script>
标签为当前运行代码所在的位置。git
须要的注意的是HTMLScriptElement.prototype.readyState
只有IE支持,Chrome
和Firefox
均不支持。github
根据上述原理,对于Document.currentScript
的polyfill实现,其实就是基于HTMLScriptElement.prototype.readyState
来实现的,具体可阅读https://github.com/JamesMGree... 的具体实现。浏览器
Document.currentScript: https://developer.mozilla.org...
Document.readyState: https://developer.mozilla.org...ui