如果脚本在全局空间中创建了任何变量或函数,您可以检查它们是否存在:
外部 JS(在全局范围内)--
var myCustomFlag = true;
并检查这是否已运行:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
更新
您可以<script>
通过选择所有<script>
元素并检查它们的src
属性来检查相关标签是否存在:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
或者您可以直接将此.filter()
功能烘焙到选择器中:
var len = $('script[src="<external JS>"]').length;