javascript - 如何使用 javascript 将相对路径的脚本注入(inject)到 html

标签 javascript typescript

当我尝试使用 javascript 将脚本注入(inject) html 页面时遇到问题。必须使用相对路径设置此脚本,就像在我的 cshtml 文件中一样:

<!DOCTYPE html>

<html>
<head>
    @{
        if (Request["debug"] != "false")
        {
            <script src='~/Scripts/script-first-debug.js'></script>
            <script src='~/Scripts/script-second-debug.js'></script>
        }
        else
        {
            <script src='~/Scripts/script-first.js'></script>
            <script src='~/Scripts/script-second.js'></script>
        }
    }

</head>
<body>
    @RenderBody()
</body>
</html>

它是我的 typescript 文件的一部分,我从 cshtml 文件中移动了这个 .net 案例:

var scriptFirst = document.createElement('script');
var striptSecond = document.createElement('script');

scriptFirst.type = 'text/javascript';
striptSecond.type = 'text/javascript';

scriptFirst.src = this.debug ? '/Scripts/script-first-debug.js' : '/Scripts/script-first.js';
striptSecond.src = this.debug ? '/Scripts/script-second-debug.js' : '/Scripts/script-second.js';

$('head').append(scriptFirst).append(striptSecond);

在本地主机上一切都很好,但是当这段代码部署到我的应用程序的生产实例上时,我遇到了问题。在我的生产应用程序实例上,我添加了一些字符串来解决问题。例如:

在本地主机上,script-first.js 的路径是:https://localhost:80/Scripts/script-first.js

在生产环境中,这个文件的路径是这样的: https://www.myproblematicapplication.com/someString/Scripts/script-first.js

你有什么建议吗? 我试图在堆栈溢出和其他页面上找到一些解决方案,但不幸的是还没有成功。

最佳答案

您的相对路径指向托管在该主机 (www.myproblematicapplication.com) 上的根文件夹 (DOCROOT/document root)。但是文件不在该文件夹中。要解决此问题,假设这些文件与将它们添加到应用程序的 typescript 文件位于同一文件夹中:

变化:

'/Scripts/script-first-debug.js' 

收件人:

'./Scripts/script-first-debug.js' 

在所有网址中。

注意前导点。这表示“在与该文件相关的同一文件夹中查找这些文件”。

关于javascript - 如何使用 javascript 将相对路径的脚本注入(inject)到 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54203746/

相关文章:

javascript - 使用免费 API 进行 GeoRedirect

javascript - HTML5 photoshop 喜欢多边形套索选择

javascript - 将一条线附加到面积图 d3 中路径的末尾

typescript - TypeScript 中的接口(interface)

javascript - 处理 Javascript 游戏中的同时 KeyEvent

javascript - D3.js 在径向树中添加元素之间的链接(分层边缘捆绑元素)

angular - 使用 Typescript 和 Angular 4 实现谷歌地图方向

javascript - Angular2引导错误: Error: No ExceptionHandler.是否包含平台模块(BrowserModule)?

typescript - 用 typescript 定义原型(prototype)函数

TypeScript 忽略 const 类型。为什么会这样编译?