views:

97

answers:

3

I have an html file that lives on www.domain-a.com

It references a js file that lives on www.domain-b.com/somedirectory/js

Within the js file I need to be able to point to www.domain-b.com but using relative paths only to a file such as www.domain-b.com/somedirectory/images

Any advice? Currently I am trying something like...

myImgUrl = '../images';

But when that is injected onto the page, that is showing up in the HTML as something like...

<img src="http://../images/somefile.jpg" />

Feedback is always appreciated.

+1  A: 

Everything JS does is relative to the environment it runs in, not where it was loaded from.

While you can do some fiddling around with the DOM to grab the last <script> element, read its src attribute and work out where the script was loaded from (assuming the script wasn't added higher up the document with DOM manipulation) … it is almost certainly going to be easier to put an absolute URI in the script (or a base URI in a variable in an inline script element higher up the document).

David Dorward
+2  A: 

You would need to hard code the image URL into the JS file you have. Otherwise, and you see, any relative reference on domain A will be just that, a relative reference to domain A.

NinjaCat
+2  A: 

Relative URLs are relative to the page they are in, so even though your script file is on the correct domain to make a relative request, the relative URL is relative to the parent page, not the script file.

Therefore, your best bet is to stick:

var domain = 'http://domain-b.com/';

Right at the top of the script and use that as a configuration item to append the image path to.

Sohnee