I\'m trying to find the best patterns for javascript usage in my sites, and in d
ID: 647248 • Letter: I
Question
I'm trying to find the best patterns for javascript usage in my sites, and in doing so I tend to look at source code at some sites (meetup.com, facebook.com, etc). One thing that sticks out at me is the fact these sites seem to compress all of their javascript and place it in the actual page rather than using a <script src="...." type="text/javascript">
My question(s):
1: How are they compressing (or how would one compress) the javascript? Should I use YUIcompress on every page call?
2: What is the benefit of doing things this way rather than importing separate scripts? I would think the separate scripts would make the page itself load quicker.
Thanks
Explanation / Answer
How are they compressing (or how would one compress) the javascript? Should I use YUIcompress on every page call?
I usually use something like UglifyJS prior to uploading my script files. Doing it every single time you have a page call doesn't seem very efficient. It's preferable to already have the JavaScript minified/compressed before you make it available as a resource on the page.
What is the benefit of doing things this way rather than importing separate scripts? I would think the separate scripts would make the page itself load quicker.
There is some debate about whether loading an external script file vs having the script inline is faster or slower. If you have the script inline it's one less resource that needs to be loaded before the page is loaded. Typically, if your script is small (less than 10-15 lines), it's better to just have it in a block on the page rather than an external file.
Google has a plugin called PageSpeed that will analyze your site and show you some ways that you can optimize it. They have a number of articles that touch on JavaScript optimization.