首页 > 解决方案 > 如何处理默认页面中的相对href

问题描述

我的应用程序托管使用 maven-dependency-plugin 下载的第三方 HTML 应用程序。默认页面是index.html,因此可以加载为http://server/parent/pathhttp://server/parent/path/index.html

默认页面使用相对地址(例如src="./somescript.js")加载样式表和脚本。这在 URL 为 时有效http://server/parent/path/index.html,但在它只是 时失败http://server/parent/path。服务器接收到请求/parent/somescript.js并返回 404。

我可以index.html在构建期间进行编辑,一种解决方案是插入一行脚本:

<script>if (!/index.html/i.test(window.location.href)) window.location.href += "/index.html";</script>

这将导航到index.html,以便始终相对于该页面请求资源。这行得通,但感觉不对。

一个正统的解决方案可能是插入一个<base>标签,但这很棘手,因为我在构建时不知道完整路径是什么——它可能是http://server/parent/path/http://server/application/parent/path/. 我不能使用绝对基本路径,而相对路径会因为与上述相同的原因而失败。

任何人都可以提出更好的解决方案吗?

标签: javascripthtml

解决方案


推荐阅读