cwa*_*ole 26
这是一个测试,看看是否已根据js文件的路径包含脚本:
function isScriptAlreadyIncluded(src){
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++)
if(scripts[i].getAttribute('src') == src) return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
它适用于所有未通过AJAX加载的脚本,但如果运行jsonp代码,可能需要修改它.
有时js文件是通过其他方式加载的(例如通过js)。
这时候就window.performance可以派上用场了。我们可以检查加载的script资源,而不是像其他答案中建议的那样检查标签,方法是:
let resources = performance.getEntries()
.filter(e => e.entryType === 'resource')
.map(e => e.name);
if (resources.indexOf("//domain.com/path/to/script.js") === -1) {
// Script was not yet loaded.
}
Run Code Online (Sandbox Code Playgroud)
现在的浏览window.performance器兼容性还不错:
https ://caniuse.com/mdn-api_performance_getentries
如果我们想要检查标记script(对于 DOM 中截至该点的所有脚本标记,包括可能尚未加载的脚本的 URL)和(window.resources对于截至该点加载的所有脚本,包括通过js),我们可以将它放在一个函数中:
function is_script_already_included(src){
const found_in_resources = performance.getEntries()
.filter(e => e.entryType === 'resource')
.map(e => e.name)
.indexOf(src) !== -1;
const found_in_script_tags = document.querySelectorAll(`script[src*="${src}"]`).length > 0;
return found_in_resources || found_in_script_tags;
}
Run Code Online (Sandbox Code Playgroud)
不使用任何框架(据我所知),您只能通过检查全局范围中的某个变量是否已经声明来做到这一点。
你可以var include1 = true;在里面声明一个变量include1.js,然后做类似的事情
if (window.include1 !== true) {
// load file dynamically
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22331 次 |
| 最近记录: |