Organizing Javascript Html And Css Code
Many web applications these days contain a ton of HTML, CSS, and JavaScript code. If you don’t have a good plan before starting to code it can get really messy really fast. It’s important to plan and organize your code well. Although we want to separate and organize our code as best as possible, the different types and pieces of code will inevitably need to be linked together in many ways.
Directories The directory structure in which your code files are organized in is something you can easily set up in the beginning of a project. A good structure will help you to separate different types of files from one another, thereby making it easier to find things when you need them. An example of a fairly good structure may be something like:
app-root resources css images blue-theme blue-theme.css js main.js img company-logo.png data lots-of-data.xml more-data.csv vendor jquery jquery-min.js index.html about.html
JavaScript There are a number of things you can do to keep your JavaScript code files organized. A few things that I usually do are:
- Keep as much JavaScript separate from the markup code as possible
- Put all dependencies at the top of each file
- Move large reusable sections of code to a separate file
- Group together similar types of functions (init functions, selectors, event bindings, etc.)
- Name functions and variables as descriptively as possible (within reason)
- Name the code files in a descriptive manor, but also concise
- Make use of namespaces when possible to keep related bits of code grouped together
CSS With CSS there are also a number of things you can do to keep the code organized. When coding my stylesheets I usually try to adhere by a few things, such as:
- Group together and label (with comments) related items
- Write each property on a separate line
- Combine multiple selectors that share the same properties e.g.: h1, h2, h3, h4 { color: #666; 0 0 .5em; }
- Avoid using universal selectors to improve performance
- Try to use classes as much as possible and avoid using IDs
- Make liberal use of white space so it is easier to read and skim
- Avoid inline styles on your markup pages when possible
- Avoid header styles on your markup pages
- Reduce complexity by separating code in separate files (within reason), and you can use tools to 'compile' them together before deployment if you so desire
- Use a CSS minifier to 'compile' your code into a smaller file for deployment to improve performance
- Layout the stylesheet such that it somewhat mirrors the page(s)/template(s). For example:
base-style.css general styles header navigation content footer [page_name]-style.css
External Resources: