Search code examples
javascriptproduction-environmenttest-environments

Load a particular JS file base on what URL its hosted


I've an MVC ASP page with the following code:

<script type="text/javascript" src="https://TEST_DOMAIN.com/test.js"> </script>
@*<script type="text/javascript" src="https://LIVE_DOMAIN.com/Live.js"> </script>*@

Essentially I comment or uncomment the script I want to use if the site is Live or if its on Test. I'd love to be able to do this dynamically some how. One solution, perhaps, is if it could read the current URL and figure out if its Live/Test.

Updated with Answer (thanks Whipdancer)

In Web.config I have added the url:

<add key="BundleJS" value="https://TEST_DOMAIN.com/test.js" />
<!--<add key="BundleJS" value="https://LIVE_DOMAIN.com/Live.js" />

I will look into web.config transformations next. But this is much better than what I had before.

The next step was during Session_Start in the Global.asax.cs file I set the url to an application variable:

Application["BundleJS"] = System.Configuration.ConfigurationManager.AppSettings["BundleJS"];

After this was set I was able to go to the controller of the view (Tip: in my case the view was a layout so I went to the parent controller). On or after the ActionResult method I added the Application variable to the viewbag

ViewBag.BundleJS = HttpContext.Application["BundleJS"];

Finally in the cshtml page (which was _layout for me) I set the script up

   <script type="text/javascript" src="@ViewBag.BundleJS"> </script>

Solution

  • Since you are using ASP.NET MVC - you can use web config transformations to handle your different environments.

    More info on web config transformations

    I would then use a web config parameter to determine the appropriate environment, that is loaded via global.asax (or possible in my primary view controller).

    You would then be able to automatically determine the appropriate URL based on the environment you compiled to.

    in test web.config:
    
    <appSettings>
        <add key="JSSource" value="https://TEST_DOMAIN.com/test.js" />
    </appSettings>
    
    in release web.config:
    
    <appSettings>
        <add key="JSSource" value="https://LIVE_DOMAIN.com/Live.js" />
    </appSettings>
    

    in global.asax you could do something like:

    public class MvcApplication : System.Web.HttpApplication
    {
        public static string jsUrl;
    
        protected void Application_Start()
        {
            jsUrl = System.Configuration.ConfigurationManager.AppSettings["JSSource"];
        }
    }
    

    In you page you could then use something like this:

    <script type="text/javascript" src="@jsUrl"> </script>
    

    ** I don't think this code will run as is. It is to give you a general idea.