0

We have a MVC site which uses subdomains. Not in the traditional sub.domain.com but instead we are using domain.com/sub. The source files all exist in the sub folders of each sub domain because each might have some slightly different things. This causes the Dev team to have to place JS directly into the razor pages so the razor code was able to update URLs like below.

var temp = $('div').load('@Url.Content("~/Images/Excel.png")');

Unfortunately using a code like below in a separate JS file tries loading from domain.com and not domain.com/sub

var temp = $('div').load('/Content/Templates/warning.html');

Theses add on to the domains and can change with clients. Is there a way to get the domain plus sub when the files are loaded like that in the JS without needing to place the code into the razor? I'd prefer a separation of concerns because we are loading scripts sometimes which aren't even used because of it.

TheHamstring
  • 712
  • 2
  • 6
  • 22
  • Take a look at [How do I make JS know about the application root?](http://stackoverflow.com/questions/34360537/how-do-i-make-js-know-about-the-application-root/34361168#34361168) – Shyju Aug 11 '16 at 12:17
  • you want a path relative to the document? for example `"./Templates/warning.html"` – Jaromanda X Aug 11 '16 at 12:21
  • I see the reference, but I'm still hoping I can exhaust any potential way of doing this without having to place something in the razor. It makes sense that I will likely have to because the JS doesn't really know about its place in the world until its loaded on the client. – TheHamstring Aug 11 '16 at 12:21
  • "./Templates/warning.html" will be in reference to the user current location. It can start too deep. – TheHamstring Aug 11 '16 at 12:23
  • You could always add the path in the `
    ` as a `data-` attribute (e.g. `
    ` and then access it your external file using `$('div').data('url')`
    –  Aug 11 '16 at 12:31

1 Answers1

1

what I always do when in similar situations is that I create a function in the main.js or whatever name your using for your shared js file, modify the URL in the function and use the function as the initiator:

in the main.js:

var loadFile = function(selector,path){
    $(selector).load('/sub'+path);
}

and then whenever and wherever you wanna load a file:

var temp = loadFile('div','/Content/Templates/warning.html');

UPDATE

you can upgrade your loadFile function to let it know if it has to load from the root of the website if needed:

var loadFile = function(selector,path,loadFromRoot){
    var root=(loadFromRoot) ? '' : '/sub';
    $(selector).load(root+path);
}
Amin Jafari
  • 7,157
  • 2
  • 18
  • 43