views:

234

answers:

3

Hi guys,

I was wondering, are you aware of any best practice for specifying absolute URLs in external javascript files? I'm looking for a maintainable solution.

The basic scenario is when i need to include css files at run-time through javascript, or make ajax calls to some URL, and other situations where you would normally need to specify URLs inside (external) javascript files.

If you were to change the server, or maybe introduce mod_rewrite, how do you prevent manually editing all the urls within the js files?

+3  A: 

Well you could build up a URL string using the following property:

var thisurl = document.location.href;

That'll give you the URL string of the current page, and hopefully you can parse it from there?

Or if you're using a server-side language (e.g. PHP) then you can grab the URL string using that, which'd be faster (this is copy-pasted from here; untested by me):

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
?>
var thisurl = <?php echo curPageURL(); ?>;

OR you could store the property in a file on the server which could be parsed by a server-side language.

Robert Grant
I pretty much do the equivalent in .NET. Would help if OP told us server side platform.
Craig
+2  A: 

You can introduce javasript class, which keeps all URLs. Something like this

function urlContainer(){
    this.searchServer = 'http://search.example.com';
    this.submitServer = 'http://submit.example.com';
}

Then reference this class in your other script files, and use URLs like:

alert (new urlContainer().searchServer);

So all your external URLs will be containted in one file. You can get more creative and use baseUrls and concatenations, but it's up to you.

PiRX
Good solution, assuming that all possible server URL's are known beforehand.
Cerebrus
It's possible to generate this file dynamically if needed.
PiRX
Indeed, this is similar to my third option, but you need to know/parse Javascript to update it :)
Robert Grant
+1  A: 

An alternative (and possibly simpler) solution might be to simply store the URL you want into a hidden field value and consequently access it using client side Javascript. Note that your Hidden field will need to be either an HtmlInputHidden or a HiddenField control. (Basically, it needs to have the runat="server" attribute so that it's value can be set on server side.)

Cerebrus