如何检查是否已包含JS文件? [英] How can I check if a JS file has been included already?

查看:118
本文介绍了如何检查是否已包含JS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将javascript拆分为不同的文件。我想阻止,javascript文件加载两次。我该怎么做?

I have split my javascript in different files. I want to prevent, that javascript files are loaded twice. How can I do that?

推荐答案

这是一个测试,看看是否已根据js文件的路径包含脚本:

Here's a test to see if a script has been included based on the path to the js file:

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;
}

它适用于所有未通过AJAX加载的脚本,尽管你可能想要如果你运行了jsonp代码,请修改它。

It will work for all scripts not loaded through AJAX, though you may want to modify it if you have jsonp code running.

这篇关于如何检查是否已包含JS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆