I am assigned a task to revise a website and at present, I am working on index.html
page. the previous coder has mixed a lot of JavaScript and CSS code in between and it is becoming difficult to read.
I want to know whether it is necessary to include <script>
tags and CSS code in between? What about PHP code? Where each must reside?
Edited:
If multiple JavaScript and CSS files are to be referenced, how to include in a single <script>
or <link>
tag?
Advertisement
Answer
Keep your JavaScript inside a separate file, keep your CSS inside a separate file and have them both referenced from within your HTML. The order of these referenced files relative to the HTML does not matter. As for the PHP, I wouldn’t worry too much about it being mixed in with the HTML (just keep your functions, classes and other scripts in separate files and include them with PHP in the header).
If is the same CSS on each page, having an external file that caches help to save bandwidth. If there are different rules intermixed with the HTML for different element types you may have some conflicts, but if you rewrite it, it will end up being a lot cleaner and easier to maintain later.
I like to keep a file structure like so:
index.php /css main.css othercssfiles.css /javascript main.js otherjsfiles.js /template header.php footer.php /scripts functions.php otherscripts.php
Then in my header file, I would place HTML code referencing the files in the CSS and JavaScript directories. And in the root directory my index.php
file would include()
; the header at the top and the footer at the bottom.
otherjsfiles.js
and othercssfiles.css
can be used in cases where a single page may have a specific requirement, requiring a lot of CSS and JavaScript that most other pages don’t need. It means other pages do not need to fetch unnecessary data and it keeps page specific code separate from the entire site’s code.
I have found this an easy way to keep track of various aspects of the code that makes up an HTML page, but naturally, you will find ways to organize it that makes sense to you.
Edited:
If multiple JavaScript and CSS files are to be referenced, how to include in a single or tag?
It would be better to combine them into a single file to conserve HTTP requests (which take time). Then you would just include those CSS and JavaScript files like normal.
<script type="text/javascript" src="/javascript/main.js"></script> <link rel="stylesheet" href="/css/main.css">
Additionally, it seems like you could use the services of a CSS beautifier for readability, a JavaScript beautifier for readability and a JavaScript minifier for when you are done reading it (keep the readable version) and want to save bandwidth. These tools are especially helpful when you are working on maintaining a website you did not create.