I’m starting to get into a lot more JavaScript thanks to a few UI frameworks such as KendoUI and Dojo/Dijit and I’m trying to integrate these with my custom MVC framework. However, all of their examples have the JavaScript embedded in <script></script> tags along with the HTML, which is fine and just means that the code gets dumped in my Views.
I was just wondering if there was some ‘standard‘ or ‘more acceptable‘ method of presenting custom JavaScript code in my projects. Is embedding the code in the HTML the best way to do it, or is it considered nicer to store the JavaScript in .js files and link to it from the HTML?
Use a script tag, for example
<script src="foo.js"></script>Ideally use a minified version, for example
<script src="foo.min.js"></script>If you’re building a website, also look into ways of caching the file (and uncaching if the files changes), for example by using a datestamp in the file name.
Some programming frameworks have ways to automatically combine and minify all the JavaScript files for a page. For example, Rails has an asset pipeline that handles this for you.