0

I was searching for ways and tricks to improve my javascript code performance. I would like to know what are the best practice to use in order to have best performance.

Does the position of the script (in the header, in the body, in the middle of the code or at the end) affect the performance?

Thanks for any tips.

Y2theZ
  • 10,162
  • 38
  • 131
  • 200
  • possible duplicate of [Does the – Felix Kling Apr 04 '12 at 09:54
  • Sorry about the duplicate. I guess i should improve my searching skills. Thanks for the link – Y2theZ Apr 04 '12 at 09:55

5 Answers5

1

If there is a lot of JS, put it at the end of the document. Although this makes no difference on load time, the user will see the page sooner and can begin to read it while your js loads, as opposed to seeing nothing until your JS is downloaded (which is what happens when you put it in the head). It merely makes the download appear faster. This would also solve the problem mentioned above about the script executing on an unfinished document, although for that, an even better solution is to use window.onload().

Chad Hedgcock
  • 11,125
  • 3
  • 36
  • 44
  • 1
    For users faster page load times can be really important. I find that moving the less important JS to the bottom of the page is a solid solution! – Kevin M Apr 04 '12 at 10:17
0

I don't think it has performance impact but it can have logic impact. If your javascript is not deferred and it tries to use a dom element declared after the script, the script will not run.

Jerome Cance
  • 8,103
  • 12
  • 53
  • 106
0

i dont think so that the position of the code will affect the performance because whenever a jsp is loaded its with all its content and script so the complete code is already present in the browser, and it wont matter where your script lies in the code.

0

Speaking without actually testing, and for any performance discussion that's dangerous, I find it hard to imagine that it will have any significant impact.

Once the code has been parsed then it's location is surely irrelevant? So the only thing that it could impact is initialisation. However I can't see that position within an HTML file can be significant, the whole file would need to be interpreted by the browser.

djna
  • 54,992
  • 14
  • 74
  • 117
0

You can place the JavaScript, anywhere within your web page. Also best practice is to load the JS at the end

  • Welocme to SO! You might like to explain your answers in details as to why it's the best practice to load JavaScript at the end of the page. – ABGR Jun 05 '20 at 14:06