Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - inline vs external script - what's the difference?

Tags:

javascript

I have a few snippets of javascript scattered about my pages - many are contained in my own .js files, however some of the stuff that I've found online sits directly on the page.

I'm not too familiar with how javascript interacts with a page - is there a difference between adding the script inline or adding a reference to the external file?

like image 822
John Ohara Avatar asked Apr 28 '15 11:04

John Ohara


1 Answers

There is little difference in using one or the other way. The real difference comes from the advantages/disadvantages that each one has.

Inline scripts

  • Are loaded in the same page so is not necessary to trigger another request.
  • Are executed immediately.
  • The async and defer attributes have no effect
  • Can be helpful when you are using a server-side dynamic rendering.

External scripts

  • Gives better separation of concerns and maintainability.
  • The async and defer attributes have effect so if this attributes are present the script will change the default behavior. This is not possible with inline scripts.
  • Once a external script is downloaded the browser store it in the cache so if another page reference it no additional download is required.
  • Can be used to load client code on demand and reduce overall download time and size.
like image 184
devconcept Avatar answered Oct 18 '22 13:10

devconcept