2

I have a site http://www.example.com

I serve my static files from a different domain. eg http://www.eg.com

in my js file which is located at http://www.eg.com/js/myscript.js

I have a variable which is an image.

var myvar = "images/example.gif";

I thought the image link would be http://www.eg.com/images/example.gif but it looks like (when I view the console) it grabs the domain name so it is getting http://www.example.com/images/example.gif

Is this expected behaviour?

Is there a way around this besides hardcoding the variable to be

var myvar = "http://www.eg.com/images/example.gif"; 

It's not ideal to hardcode as if the domain changes I will then need to update it twice?

ak85
  • 4,154
  • 18
  • 68
  • 113

2 Answers2

1

All relative links are relative with respect to what you see in the address bar of the browser.

The only exception to this are images loaded in CSS (eg background-images), in which case paths are relative to the CSS file.

Edit: Though I haven't used it personally, W3C seems to define the base tag which could work for what you want

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
  • Thanks I thought I had seen it used somewhere before. It must have been in a css file. – ak85 May 20 '13 at 07:57
1

It is the expected behavior because it's relative to the current URL.

If you need to use a different domain for your links/images then I would add a var to hold the host name and reference it in your JS file so you only have to change it in one place if you move the file.

So:

var domain = 'http://eg.com/';
var myvar = domain + "images/example.gif";

Or if you don't want to hardcode the domain, you could pull it from the JS source attribute:

HTML:

<script type="text/javascript" id="myjs" src="http://eg.com/myscript.js"></script>

Inside myscript.js:

var myjs = document.getElementById('myjs');
var domain = myjs.getAttribute('src').replace('myscript.js','');
var myvar = domain + "images/example.gif";

You could also just use the base tag in your header but there are some gotcha's.

Community
  • 1
  • 1
Justin
  • 26,443
  • 16
  • 111
  • 128
  • thanks, I have used the base tag in some cases in the past. I'll keep your other suggestions in mind for the future as well. – ak85 May 20 '13 at 20:39