HTML相对于图像的路径。在Github页面上找不到404

时间:2017-02-02 14:37:55

标签: javascript html image url github-pages

我有以下文件结构

demo  
|_ assets  
.....|_ image.png  
.....|_ anotherimage.png  
|_ dist  
.....|_ my-component.html  
.....|_ my-component.js  
|_ index.html  

my-component.html<img src="../assets/image.png"/> my-component.js在运行时生成<img src="../assets/anotherimage.png"> HTML标记。

这在我的本地http服务器上工作正常 当我把东西推到Github Page时会出现问题。

  • 正确显示my-component.html文件中提到的图像。它将图片网址识别为http://myorg.github.io/myrepo/demo/assets/image.png
  • my-component.js文件中提到的图像找不到404。它将图片网址识别为http://myorg.github.io/myrepo/assets/anotherimage.png

注意浏览器识别的两种情况的网址。第二种情况没有demo/

就像my-component.js位于demo目录而不是dist。但是如何发生这种情况。这有什么问题?我该如何解决?

被修改
有问题的my-component.htmlmy-component.js实际上是Polymer组件分成2个文件,一个用于模板,另一个用于逻辑代码。 然后index.html通过代码顶部的<link rel="import" href="dist/my-component.html">在该组件中导入。聚合物没有问题,或者之前我测试过它,我不认为问题涉及聚合物。

1 个答案:

答案 0 :(得分:1)

在WebComponents中,路径是相对于HTML页面的,在Polymer中,它们是相对于组件本身的。见https://stackoverflow.com/a/33603356/227299

possible solution是使用this.resolveUrl('../assets/image.png')相对于JS文件创建路径。