简体   繁体   English

动态更改相对图像路径

[英]Dynamically changing a relative image path

I have a page that is including an HTML pattern from a separate folder. 我有一个页面,其中包含来自单独文件夹的HTML模式。 That HTML has a relative image path that I need to change so that I can load the image from the included HTML, as well as from the source HTML. 该HTML具有我需要更改的相对图像路径,以便可以从包含的HTML以及从源HTML加载图像。

source.html source.html

<div>
    <svg class="icon">
        <use xlink:href="../../assets/svg/spritemap.svg#icon-close" />
    </svg>
</div>

index.html, including the same snippet, but the path needs to change to just assets index.html,包括相同的代码段,但路径需要更改为仅资产

<div>
    <svg class="icon">
        <use xlink:href="assets/svg/spritemap.svg#icon-close" />
    </svg>
</div>

I'm using this javascript to change the path on the source.html page: 我正在使用此javascript来更改source.html页面上的路径:

setTimeout(function() {
$('img').each(function(){
var $this = $(this);
$this.attr('src',$this.attr('src').replace('assets','../../assets'));
});
$('use').each(function(){
var $this = $(this);
$this.attr('xlink:href',$this.attr('xlink:href').replace('assets','../../assets'));
})
}, 500);

Which searches for paths on IMG and USE tags and appends the "../../" portion so the file can be found. 它在IMG和USE标签上搜索路径,并附加“ ../../”部分,以便可以找到文件。 There's a timeout associated to allow for the page to load. 有一个超时允许页面加载。

However, the assets are not loading in the source.html page reliably. 但是,资产无法可靠地加载到source.html页面中。 Sometimes they load, sometimes not. 有时它们加载,有时不加载。

What is the best way to dynamically change a relative image path on separate pages? 在单独的页面上动态更改相对图像路径的最佳方法是什么? Should I be using a baseURL variable or something? 我应该使用baseURL变量还是其他?

I don't think your strategy is crazy. 我认为您的策略并不疯狂。 There is a cleaner js based solution using a base URL pulled from a single data attr of the given page, but I suspect your issue is just loading sequence. 有一个更清洁的基于js的解决方案,使用从给定页面的单个数据属性中提取的基本URL,但是我怀疑您的问题只是加载顺序。 Have you tried running your code inside of document ready, instead of a setTimeout? 您是否尝试过在文档内部而不是setTimeout中运行代码?

Or better yet, running your code in window load, which will ensure that the DOM and all assets have been loaded first: 或者更好的是,在窗口加载中运行代码,这将确保先加载DOM和所有资产:

$( window ).load(function() {

//put all your code in here

});

---EDIT--- - -编辑 - -

It looks like from your comments above that the only distinction between files is a dev versus production environment. 从上面的评论看来,文件之间的唯一区别是开发环境与生产环境。 That still would point to a more robust javascript solution, but if the files are static, then why not do the processing/decision making locally and then only upload the relevant html file? 那仍然会指向一个更强大的javascript解决方案,但是如果文件是静态的,那么为什么不在本地进行处理/决策,然后仅上传相关的html文件呢? Either by hand, or using a Grunt/Gulp type of deployment scripts. 可以手动,也可以使用Grunt / Gulp类型的部署脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM