0

i am wondering what is better for performance including your js file under your html code or having a separate js file for example

index.html

<html>
<head></head>
<body>
<button id="done">click me!</button >
<script>
 $( "#done").click(function(e) {
   alert("Hello");
 });
</script>
</body>
</html>
  • or

index.html

<button id="done">click me!</button >

custom.js

 $( "#done").click(function(e) {
   alert("Hello");
 });
1
  • This depends on size of the javascript, html file. Readability is the first thing you need to consider. next is http timeout, does your page break if your js file doesn't download or doesn't download on time? Commented Jul 26, 2019 at 2:07

1 Answer 1

2

In terms of code compilation and execution speed, both are the same, code is code.

However for page load speed this is actually not as simple as people think.

For a small page with a small amount of code - Inline JS would be faster.

This is because you don't have the round-trip time waiting for the Javascript to load (especially on a mobile connection where it can take 350ms for a request to get to a server and back).

As the size of your JS increases though the fact that you can download several files in parallel more than offsets the time required to fire up a connection to the server.

Unless you are really squeezing every last bit of performance out of the page use external scripts (and even if you are going for top speed keep your JS below 20kb GZIPped or it isn't worth it).

If you want to improve load speed use 'async' or 'defer' (async is the preference if your JS doesn't rely on load order) and add them to the HEADER of the page (this is contrary to most advice but because they are deffered or async they do not block rendering and are requested sooner).

If you want performance gains

inline the CSS required to render everything 'above the fold' - THAT makes a site feel lightning fast (but it is harder than you think).

Spend more time on minimising the number of requests and the size of files.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.