位于不同域的 JS 文件的相对路径
我有一个位于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
相对 URL 是相对于它们所在的页面的,因此即使您的脚本文件位于正确的域中以发出相对请求,相对 URL 也是相对于父页面的,而不是相对于脚本文件的。
因此,最好的选择是将:
放在脚本的顶部,并将其用作配置项来附加图像路径。
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:
Right at the top of the script and use that as a configuration item to append the image path to.
JS 所做的一切都与它运行的环境相关,而不是与它的加载位置相关。
虽然您可以对 DOM 进行一些摆弄以获取最后一个
元素,但读取其
src
属性并计算出脚本的加载位置(假设脚本没有通过 DOM 操作添加到文档的较高位置)…几乎可以肯定,在脚本中放置绝对 URI(或者在文档较高位置的内联脚本元素中的变量中的基本 URI)会更容易。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 itssrc
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).您需要将图像 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.