What is the difference if i include java script in normal HTML tag and include .js file in my page ??
5 Answers
Not much. It is recommended that you move your JavaScript and CSS to external files mainly because browsers are able to cache these files between different requests. This advantage is most evident when your site makes use of dynamic content, and therefore the browser cannot retrieve the HTML from the cache.
1 Comment
Having JS in a file makes it more modular so you can reuse that code over a number of pages.
Since its a different file means that you can use 1 download stream for the HTML and 1 for the JS making the page load a little quicker.
You can also minify and obstificate JS when it is in another file making it quicker to download.
Comments
If you have javascript code in head element and if will be executed before your page is rendered in the browser, then it will degrade the user experience in some browsers.
If you are using javascript code inline, and in body using script tag, it will be executed as soon as it encountered. Again, it will delay loading of your page after that specific tag.
It is a better practice to:
- Separate it in .js file
- Add the script reference at the end of file