Search code examples
jqueryhtmlloadrelative-pathabsolute-path

Use relative path for both jquery load and direct link to html page


On my website I use links to load html pages within a div.

<a class="iframe" href="portfolio/1/1.html">Link</a>

code

$(".iframe").on("click", function() {
   var $mylink = $(this).attr('href');
   $div.load($mylink);
}

If I open one of those links in a new tab, css and images do not load because I use relative paths since the html pages end up inside a div. By using absolute paths on the html pages I can get them to load but that causes css to load twice when the links load inside the div (and not on a new tab).

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/main.css" type="text/css" media="screen"/>
</head>

<body>
<div>
<img src="portfolio/1/1.jpg"/>
</div>
</body>
</html>

Is there a way to use relative paths only and come around this issue? Basically I want the html pages to load inside the div as they do, but if the user opens the html page directly to still be able to load the content correctly (without using absolute paths if possible).


Solution

  • Use the base tag to specify a base url. All relative links within a html document will be relative to your base https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base