In this blog post I’m going to talk about the wrong and right way to layout your front side assets. By this, I mean the html, js, images and css files.
What’s the Big Deal?
2. Assets can be bundled. MVC and the newer .Net websites can perform automatic bundling of js and css files.
3. Assets can be minified. MVC and the newer .Net websites can perform automatic minification. This will cause web pages to load faster.
4. You can upload your js and css files to a CDN for faster distribution, reducing the load on your web servers.
How to Convert Your Code
Front-side HTML code:
<input type=’hidden’ id=’myVariable’ value='<%=variabledata %>’ />
var myVariable = $(‘#myVariable’).val;
Or, if you’re using Razor, you can use the viewbag instead of the ugly “<% %>” tags.
var myVariable = ‘<%=variabledata %>’;
var MyOtherVar = ‘<%=variabledata %>’;
// jquery function code here
This will eliminate a lot of clutter inside your HTML code. You’ll need to make sure that your HTML has the proper id tags so you can attach event handlers to your code.
Remove all your in-line style codes. Move these to a style sheet. One of the benefits of containing all of your css in style sheets, is that you can use a css pre-processor like “less”. Less is a language that can extend the power of css, making it more dynamic. For more information about less go here.
You can also change your website theme by switching css files. If you created a lot of in-line css, you’re stuck. This code is embedded with your HTML and would need to be altered using variables (like color and background-color for example). The css pages for each theme can be stored along with the images that match the theme. Then the path names provided at the top of a web page can be setup as variables controlled by the code-behind or controller.
Content Delivery Networks
When you use CDN’s you’ll need to pre-minify your JS and CSS files, instead of doing this automatically. There are a lot of programs available that will minify these types of files and you can include this in your deployment process.