document.ready在外部JS文件中,用于检测加载哪个文件

document.ready in external js files which detect which file is load

本文关键字:文件 用于 检测 加载 ready 外部 JS document      更新时间:2023-09-26

我有一个包含多个html文件的文件结构。每个文件都有一个包含到同一个 js 文件。有些代码仅用于 document.ready 函数中的索引.html而其他代码可能仅用于帮助.html。所以这是我的问题:

如果我访问索引.html(帮助相同.html,是否有一个干净的解决方案可以在 document.ready 函数(在 ext js 文件中定义)中仅运行索引所需的代码片段.html?

注意:我想将所有JS代码存储在外部js中。我知道,我可以将所需的代码片段存储在每个文件的标头中,但我真的只想将整个 js 代码存储在一个 ext 文件中。

你有几个选择

1)您可以查询URL document.URL并确定它是否与您想要的匹配,并在if块中执行。 例如

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
if (document.URL.endsWith('testDir/index.html')) {
    //do logic.
}

2)你也可以在你的索引上放一个特殊的div id/class/etc

<div id='divImInIndex'></div>
if ($('#divImInIndex').length > 0) {
    //do logic
}

可能还有其他方法...但这绝对不符合最佳实践。 我相信在我提出的两个中,#2 是更好的选择,仅仅是因为您不确定是否发生了 url 重写,或者服务器是否加载了默认文档(例如,url 可能/testDir/,因此服务器提供/testDir/index.html