1

I am reading book "Pro PHP and jQuery", I see: enter image description here

but Stack Overflow put jQuery call at near top: enter image description here

My question is:

Is best practice when put script link jQuery at the end near inside HTML page?

Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • Yes, if you can get away with this, then having jQuery at the bottom of the doc, or async loading it will make the page load faster, but scripts that depend on jQuery may not work if placed _before_ the jQuery script. Most modern sites have jQuery at the top for this reason. – Drakes Aug 28 '16 at 15:21

1 Answers1

1

Yes it is. You should put all JavaScript <script> tags and links at the end, and here is why.

Classic HTML

Load Time

The browser needs to load those files, which means the client downloads them. While this does happen very quickly, we would prefer that the client looks at some page rather than a white screen. Depending on their internet connection the download can take a couple milliseconds, or possibly a couple seconds. So better safe than sorry.

Dependence on DOM

Javascript and jQuery often manipulate the DOM. So the DOM needs ot be loaded in order for JavaScript to work

HTML 5

Appreciated form @Vohuman

It should be noted that HTML5 has introduced async and defer attributes that can change the behavior of script tags!

For beginners that may not understand asynchronous programming, check out this link

Async Attribute

Adding this attribute to a script element like so <script async> will cause the script to be downloaded to the client while the HTML DOM is loading (images, divs, etc.).

Defer Attribute

This attribute will download the script async, and then execute it once the DOM is fully loaded. Use like this <script defer>.

Community
  • 1
  • 1
Hurricane Development
  • 2,449
  • 1
  • 19
  • 40