To handle relative paths in a website I use a <base>
tag added in the <head>
of every page.
All the resources loaded through a relative-like path in the documents are properly fetched and shown, however the browser (Chrome and Firefox in my trials) load every asset twice, one time with the real relative path (giving a 404 error) and a second time with the <base>
tag appended before it.
I implement such tag with this script manually written in every html file:
<head>
<script>
/* Where am I? */
here = window.location.href;
hereIndex = here.indexOf('prd-ita'); //find path to main folder
/* make substring from local root till prd-ita/ */
newPathname = here.substring(0, hereIndex+10); //+8 to consdier also prd-ita/
document.write('<base id="host" href="' + newPathname + '"/>');
</script>
...
</head>
For instance and to clarify, my folder structure is for example:
- prd-ita
- index.html
- folder1
- file1.html
- pic.jpg
- subfolder2
- file2.html
Regardless of which html file is loaded the generated href for the base tag is file:///D:/myWebsite/prd-ita/
and into file2.html I load a resource with the path src="folder1/pic.jpg"
.
From the inspecting tool I see that two loading attempts are made:
- Wrong path (real relative path interpreted)
file:///D:/myWebsite/prd-ita/folder1/subfolder2/folder1/pic.jpg
- Correct path (base tag appended)
file:///D:/myWebsite/prd-ita/folder1/pic.jpg
Before you ask I wont use the /
to begin my relative paths because it is interpreted just as the drive letter where the file is located and I need the full path to the main prd-ita folder. I want to use only client side code (no php for example).