Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it right to write multiple and separate <script > on a page?

While writing JavaScript code, I Separate each code block with <script> tags

<script type="text/javascript">
 //---- code block 1--------- 
</script>   

<script type="text/javascript">
    ----code block 2-----
</script>

<script type="text/javascript">
$(document).ready.(function(){
 // code block3
});
</script>

I want to know that is it good practice to write separate <script type="text/javascript"></script> on the same page

--or--

We have to write all JavaScript code under one <script>

What are the technical differences in each way?

like image 578
diEcho Avatar asked Apr 23 '10 12:04

diEcho


3 Answers

Well, you may want to ask yourself why your code organization scheme leads to that setup, and whether it causes maintenance or understandability problems, but I don't think it's strictly "bad". Now if your <script> tags are actually fetching separate files from the server, then it's a good idea to cut back on them.

The browser parses and interprets script tags in such a way that other work stops, so blocks of Javascript up at the top of your page can slow things down if they do a lot of work. That's true whether you've got a big block of code or several smaller blocks, however.

An advantage of moving to separate script files is that you can re-use code on multiple pages. When you do that, it may be easier at build time to compress your scripts with YUICompressor or some other similar tool.

like image 74
Pointy Avatar answered Oct 12 '22 02:10

Pointy


The best reason to do this is if each script represents a discrete chunk of functionality which may not be used on (and therefore not vended to) every page. In that case, it becomes a smart strategy.

like image 20
Robusto Avatar answered Oct 12 '22 03:10

Robusto


Having multiple <script> tags makes no real difference in performance but is less readable.

like image 35
hunter Avatar answered Oct 12 '22 03:10

hunter