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:
- Will work for:
http://localhost/v1/foo/bar/page.aspx
- Will not work for:
http://localhost/v1/foo/page.aspx
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.
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.
I would do
location.origin + "/" + location.pathname.split("/")[1] + "/images/awesome.jpg"
-Sorry for the convoluted regex.-
Edit:
better yet ^
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?
精彩评论