带有HTML导入的JS中的相对路径资源 [英] relative path resources from JS with HTML imports

查看:312
本文介绍了带有HTML导入的JS中的相对路径资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个(聚合物)Web组件,我想以跨域资源共享(CORS)的方式使人们可以访问.除我不确定如何从该组件内的JS代码中提供诸如图像和JSON文件之类的资源的相对路径外,其他方法都可以正常工作.它们被解释为相对于包含页面,而不是相对于HTML导入.我想想的是一个JS变量,它给出了导入的包含html文件的路径.相对路径很重要,因为我还希望人们能够轻松地将此路径部署到自己的站点,而不要依赖于我的资源副本的硬编码路径.

例如,您在example.com上加载index.html,它具有:

<link rel="import" href="//my-site.com/components/my-component/my-component.html">

<my-component> ... </my-component>

现在在my-component.html内部,我有一些JS可以根据用户的配置文件加载一些资源-i18next.js的图像和JSON语言文件.问题是,除非我将它们指定为my-site.com的绝对路径(我不想这样做),否则它们将被解释为相对于example.com/index.html的页面,而不是相对于my-component.html <的路径/p>

我在模板中静态指定的任何图像都可以正常工作并正确加载,因为它们是相对于HTML导入路径的.我只是不确定如何对从JS加载的资源执行此操作,因为它们将相对于包含页面(example.com/index.html).某处是否存在公开此导入路径的属性或函数?谢谢.

解决方案

要创建相对路径,可以使用Polymer元素的resolvePath方法. 此处是文档

例如:this.resolvePath('x-foo.png')

更新:resolvePath替换为

Now inside my-component.html, I have some JS that loads some resources based on the user's profile - images and JSON language files for i18next.js. The problem is that unless I specify them as an absolute path to my-site.com, which I don't want to do, they will be interpreted as relative to the page at example.com/index.html, not relative to the path of my-component.html

Any images that I specify statically in my template work fine and load correctly because it's relative to the HTML Import path. I'm just not sure how to do this for resources loaded from JS because they will be relative to the containing page (example.com/index.html). Is there an attribute or function somewhere that exposes this import path? Thanks.

解决方案

To create relative paths you can use the resolvePath method of your Polymer element. Here's the docs on it

ex: this.resolvePath('x-foo.png')

Update: resolvePath is replaced with resolveUrl for Polymer 1.0

这篇关于带有HTML导入的JS中的相对路径资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆