relative path resources from JS with HTML imports

一世执手 提交于 2019-12-19 10:24:41

问题


I've got a (Polymer) web component that I want to make accessible to people in a cross-origin resource sharing (CORS) fashion. That works fine except I'm not sure how I can give a relative path for resources like images and JSON files from JS code inside that component. They are interpreted as relative to the containing page, not relative to the HTML import. What I think I want is a JS variable that gives the path of the containing html file that was imported. A relative path is important because I also want people to be able to easily deploy this to their own site and not rely on a hardcoded path to my copy of a resource.

For example, you load index.html at example.com and it has:

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

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

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.


回答1:


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




回答2:


I found out that you can access the URL of the import from within a script inside it with document.currentScript.baseURI. I'm doing something like this:

<script>
    (function () {
        var srcURL = new window.URL(document.currentScript.baseURI);
        var baseURL = srcURL.origin + srcURL.pathname.substr(0, srcURL.pathname.lastIndexOf("/") + 1);

        // can use baseURL here to load resources
        Polymer({...});
    })();
</script>

One problem: the code above isn't working when I vulcanize everything because the paths change. I'll look into that one a bit later.



来源:https://stackoverflow.com/questions/29034037/relative-path-resources-from-js-with-html-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!