位于不同域的 JS 文件的相对路径

发布于 2024-09-15 07:18:19 字数 408 浏览 2 评论 0原文

我有一个位于 www.domain-a.com 上的 html 文件

它引用了位于 www.domain-b.com/somedirectory/js 上的 js 文件

在 js 文件中,我需要能够指向 www.domain- b.com,但仅使用文件的相对路径,例如 www.domain-b.com/somedirectory/images

有什么建议吗?目前我正在尝试类似...

myImgUrl = '../images';

但是当它被注入到页面上时,它会在 HTML 中显示为类似...

<img src="http://../images/somefile.jpg" />

反馈总是值得赞赏的。

I have an html file that lives on www.domain-a.com

It references a js file that lives on www.domain-b.com/somedirectory/js

Within the js file I need to be able to point to www.domain-b.com but using relative paths only to a file such as www.domain-b.com/somedirectory/images

Any advice? Currently I am trying something like...

myImgUrl = '../images';

But when that is injected onto the page, that is showing up in the HTML as something like...

<img src="http://../images/somefile.jpg" />

Feedback is always appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月隐月明月朦胧 2024-09-22 07:18:19

相对 URL 是相对于它们所在的页面的,因此即使您的脚本文件位于正确的域中以发出相对请求,相对 URL 也是相对于父页面的,而不是相对于脚本文件的。

因此,最好的选择是将:

var domain = 'http://domain-b.com/';

放在脚本的顶部,并将其用作配置项来附加图像路径。

Relative URLs are relative to the page they are in, so even though your script file is on the correct domain to make a relative request, the relative URL is relative to the parent page, not the script file.

Therefore, your best bet is to stick:

var domain = 'http://domain-b.com/';

Right at the top of the script and use that as a configuration item to append the image path to.

↙厌世 2024-09-22 07:18:19

JS 所做的一切都与它运行的环境相关,而不是与它的加载位置相关。

虽然您可以对 DOM 进行一些摆弄以获取最后一个

Everything JS does is relative to the environment it runs in, not where it was loaded from.

While you can do some fiddling around with the DOM to grab the last <script> element, read its src attribute and work out where the script was loaded from (assuming the script wasn't added higher up the document with DOM manipulation) … it is almost certainly going to be easier to put an absolute URI in the script (or a base URI in a variable in an inline script element higher up the document).

江湖正好 2024-09-22 07:18:19

您需要将图像 URL 硬编码到您拥有的 JS 文件中。否则,您会看到,域 A 上的任何相对引用都只是对域 A 的相对引用。

You would need to hard code the image URL into the JS file you have. Otherwise, and you see, any relative reference on domain A will be just that, a relative reference to domain A.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文