user47589
user47589

Reputation:

Keeping urls relative?

We have multiple versions of our web app each running in their own virtual folders off the root. On development machines, the app is running out of the root:

http://localhost/              
http://localhost/v1
http://localhost/v2

Each application has many folders and many pages. The images are all in an ~/images folder:

http://localhost/images/awesome.jpg
http://localhost/v1/images/awesome.jpg
http://localhost/v2/images/awesome.jpg

http://localhost/index.aspx
http://localhost/v1/index.aspx
http://localhost/v2/index.aspx

http://localhost/foo/warble.aspx
http://localhost/v1/foo/warble.aspx
http://localhost/v2/foo/warble.aspx

Now, in my javascript I need to refer to one of these images, but it needs to be in that version's folder. I don't necessarily know what page is using this Javascript. How can I insert a relative URL to an image? Sure, I could use something like ../../images/awesome.jpg, but that would only work for pages that are two folders removed from the root:

I can't use an absolute path because of the versioning aspects of the app hosting. Any ideas how I can get past this most troublesome roadblock? I am tagging jQuery in case there's some jQuery library function that can handle this.

Upvotes: 1

Views: 247

Answers (3)

Mika Tähtinen
Mika Tähtinen

Reputation: 983

You need to pass the images directory url to javascript from the server side code somewhere on each page you'll need. Consider putting it inside the <head> element in the layout and before the javascript files that will be needing it.

<script>
  var imagePath = '<%=Page.ResolveUrl("~/images/") %>';
</script>

and with MVC razor engine:

<script>
  var imagePath = '@Url.Content("~/images/")';
</script>

And then use the global variable imagePath in your javascript files to link to your images:

img.src = imagePath + 'image01.jpg';

Another solution is to use CSS which can handle relative paths by linking to a CSS file in the images directory and using the images in javascript via CSS classes and ids.

Upvotes: 2

joelmdev
joelmdev

Reputation: 11773

My initial thought is that you can pull this off by either using an Http Handler or by using IIS's URL Rewrite module. Will your production site look like "mysite.com/v1" etc?

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78530

I would do

location.origin + "/" + location.pathname.split("/")[1] + "/images/awesome.jpg"

-Sorry for the convoluted regex.-

Edit:

better yet ^

Upvotes: 0

Related Questions