javascript - Set Relative link in a js file to come from files source rather than domain -


i have site http://www.example.com

i serve static files different domain. eg http://www.eg.com

in js file located @ http://www.eg.com/js/myscript.js

i have variable image.

var myvar = "images/example.gif"; 

i thought image link http://www.eg.com/images/example.gif looks (when view console) grabs domain name getting http://www.example.com/images/example.gif

is expected behaviour?

is there way around besides hardcoding variable

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

it's not ideal hardcode if domain changes need update twice?

it expected behavior because it's relative current url.

if need use different domain links/images add var hold host name , reference in js file have change in 1 place if move file.

so:

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

or if don't want hardcode domain, pull 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 use base tag in header but there gotcha's.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -