Skip to content

Problems with JavaScript files references and MVC/SEO friendly applications

JavaScript, unlike CSS, is executed relative to the path of the html page that contains the JavaScript code. This introduces some difficulties in you have a typically MVC application using SEO friendly links. Why? Because JavaScript doesn’t have the concept of a “base” url, or any way to define it. So if you want to reference a url resource in JavaScript, but don’t want to hard code the urls, what can you do?

Print to your <head /> tag in your main page template a JavaScript variable that defines the path to the theme – you can then reference this variable in your JavaScript code using it as a “base”. That lets you keep your JavaScript code nice and modular…

I’ve used this is a few times when coding custom Magento or WordPress themes and it saves a little bit of pain when transferring from the Development to Live server…

<script> var themePath = '';</script>
<script> var swfPath = themePath + '/images/swf/';</script>
This entry was posted in Web Development. Bookmark the permalink.


Sorry, comments are closed on this page.