Resolve a Javascript file inside a MasterPage

The issue:

There are times when you structure your website layout differently such as admin pages would be under /admin folder and so forth. Since MasterPage files doesn't resolve an incorrect path to a local Javascript folder and file, your scripts will not work. Oddly enough, the CSS file path location is resolved automatically and it determines the proper location of where the CSS file is regardless of the page location.

The solution: 

  • Host your Javascript source file else where in a remote location and provide the absolute URL to the script. A perfect example of this is having your jQuery hosted on a Google Cloud Network (CDN). <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>. While this works, it's not recommended for secured sites since you're requesting a file from an unsecured site.
  •  Use ResolveClientUrl() method in your server-side code or declaratively such as <script src='<%= ResolveClientUrl("~/js/jsfile.js") %>' type="text/javascript"></script>.

Hope this helps people who encounters this issue.

- Dennis
menacestudio.com / codeoverload.net

4 Comments

Comments have been disabled for this content.