Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: include( or <script src="

I have minified my javascript and my css.

Now, Which is better?

<script type="text/javascript">
<?
  $r = file_get_contents('min.js');
  if($r) echo $r;
?>
</script>

OR

<script type="text/javascript" src="min.js"></script>

Same question for CSS.

If the answer is 'sometimes because browsers fetch files simultaneously?' Which browsers, and what are examples of the times in either scenario.

like image 635
Issac Kelly Avatar asked Oct 07 '08 12:10

Issac Kelly


People also ask

What is the best practice to use script tag?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.

Where should I put script src?

Using the script tag to include an external JavaScript file The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Should script be inside body or outside?

Using the script tag to include an external JavaScript fileThe script tag should either be included between the <head> tags or just before the closing <body> tag in your HTML document. JavaScript is often placed before the closing body tag to help reduce the page loading time.

Why do we use script src?

Definition and Usage. The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.


1 Answers

<script type="text/javascript" src="min.js"></script>

...is better, as the user's browser can cache the file.

Adding a parameter to the src such as the file's last modified timestamp is even better, as the user's browser will cache the file but will always retrieve the most up to date version when the file is modified.

<script type="text/javascript" src="min.js?version=20081007134916"></script>
like image 69
Jonny Buchanan Avatar answered Sep 28 '22 20:09

Jonny Buchanan