我为我的网站编写了一个简单的 404 页面,每次加载时都会告诉您一个笑话。我通过使用 StackExhange API 来完成此任务,并从 this thread 中提出问题。 .
当我故意使用垃圾文件 URL 触发 404 页面时,一切都会按预期进行。例如,当我转到www.domain.com/garbage
时,404 页面按预期加载。我的404.shtml
有一个script
加载 404.js
的标签我写的脚本,一切都很棒。
但是,当我尝试通过路由到与垃圾文件相对应的垃圾目录来获取404页面时,找不到脚本。例如,www.domain.com/garbage/
不加载404.js
尽管脚本正确404.shtml
页面正在加载。
这是 head
我的 HTML 文件的部分。
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script src="404.js" type="text/javascript"></script>
</head>
注意:外部 jQuery 脚本两次加载,但是 404.js
仅针对第一个请求示例加载。
这里是两个请求的控制台,第一个是垃圾文件的请求,第二个是垃圾目录的请求。
第一个网址: www.domain.com/garbage
// a long JSON response from the StackExhange API that indicates that the script loaded
第二个网址: www.domain.com/garbage/
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (404.js, line 0)
问题是什么导致了 404.js
当我尝试访问无效文件时加载相同的脚本时,当我尝试访问站点内的无效目录时,脚本不会被加载?
我尝试过的
- 大量的 Google 搜索。
- 三次检查所有脚本标签是否都指向正确的文件
感谢您的宝贵时间。如果您想进行更多挖掘,您可以在briantracy.xyz/garbage
查看实际问题。和briantracy.xyz/garbage/
.
最佳答案
非常感谢@rfornal建议为脚本创建相对文件路径。更改 head
部分中的以下行
<script src="404.js" type="text/javascript"></script>
^^^^^^
通过将根目录(404.js
所在位置)添加到文件路径前面即可实现此目的。
<script src="/404.js" type="text/javascript"></script>
^^^^^^^
关于javascript - 当 URL 为目录时,JS 文件无法加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518357/