133

I would like to know when I should include external scripts or write them inline with the html code, in terms of performance and ease of maintenance.

What is the general practice for this?

Real-world-scenario - I have several HTML pages that need client-side form validation. For this I use a jQuery plugin that I include on all these pages. But the question is, do I:

  • write the bits of code that configure this script inline?
  • include all bits in one file that's share among all these HTML pages?
  • include each bit in a separate external file, one for each HTML page?

19 Answers 19

118

At the time this answer was originally posted (2008), the rule was simple: All script should be external. Both for maintenance and performance.

(Why performance? Because if the code is separate, it can easier be cached by browsers.)

JavaScript doesn't belong in the HTML code and if it contains special characters (such as <, >) it even creates problems.

Nowadays, web scalability has changed. Reducing the number of requests has become a valid consideration due to the latency of making multiple HTTP requests. This makes the answer more complex: in most cases, having JavaScript external is still recommended. But for certain cases, especially very small pieces of code, inlining them into the site’s HTML makes sense.

27
  • 6
    @Nick: most problems can be overcome. Better not to generate them in the first place, though. Oct 15, 2008 at 8:16
  • 18
    Sometimes you get better performance when inlining. Look at the source of google.com. They know what they're doing.
    – callum
    Apr 12, 2012 at 10:04
  • 16
    @callum Google has a different use-case from 99.999999% of websites. Of course they measure extremely carefully and even the smallest difference matters. But just because they found that in their particular use-case, inlining works better (probably because the script changes very frequently?) doesn’t mean that we can derive a general rule from that, or even that we should disregard the “conventional” rule (to externalise scripts). Apr 12, 2012 at 10:16
  • 8
    @KonradRudolph - Agreed, no general rule should be derived from Google's approach. I'm just saying it's a hint that it might be worth questioning the rule in your answer. Anyway, I think the reason Google does it is to reduce HTTP requests, and this might benefit more than 0.000001% of sites. Bandwidth is getting higher but round trip times are staying the same. Removing a whole serial HTTP request is sometimes better than the caching benefit of external JS. Depends on the size of your JS of course.
    – callum
    Apr 13, 2012 at 10:28
  • 5
    @callum While this is true, the point about caching still remains and stays important. Reducing roundtrips is only important if your visitors don’t return (and then you won’t get enough page hits to make it matter) or if your content changes so often that caching the script files has no benefit. Apr 13, 2012 at 10:30
31

Maintainability is definitely a reason to keep them external, but if the configuration is a one-liner (or in general shorter than the HTTP overhead you would get for making those files external) it's performance-wise better to keep them inline. Always remember, that each HTTP request generates some overhead in terms of execution time and traffic.

Naturally this all becomes irrelevant the moment your code is longer than a couple of lines and is not really specific to one single page. The moment you want to be able to reuse that code, make it external. If you don't, look at its size and decide then.

5
  • 5
    That's one of my concerns. Having a separate HTTP request for a few lines of codes seems wasteful.
    – Dan
    Sep 26, 2008 at 13:01
  • Could you perhaps post a sample configuration for your code? IMO if it's under 300 characters and absolutely page-specific, inline it. Sep 26, 2008 at 15:22
  • @Dan bear in mind that the separate request only happens the first time. If you expect your users to be loading the page more than once, cached external (even for a few lines) is clearly faster than waiting for the bytes for those few lines over the wire on the n=2+ page loads. May 2, 2018 at 17:16
  • @HorstGutmann how does having the file external aid with maintainability? I personally prefer external js whenever possible, but is there something objective that makes it easier to maintain? May 16, 2018 at 23:12
  • @jinglesthula one example would be if you want to use the same code (or something quite similar) on multiple pages. Have the same code live in multiple places hinders maintainability. Sure, there are ways around that, but let's just assume the most naive implementation here. It's also far easier to statically analyse code when it lives in dedicated files (eslint et al.). May 18, 2018 at 19:51
22

If you only care about performance, most of advice in this thread is flat out wrong, and is becoming more and more wrong in the SPA era, where we can assume that the page is useless without the JS code. I've spent countless hours optimizing SPA page load times, and verifying these results with different browsers. Across the board the performance increase by re-orchestrating your html, can be quite dramatic.

To get the best performance, you have to think of pages as two-stage rockets. These two stages roughly correspond to <head> and <body> phases, but think of them instead as <static> and <dynamic>. The static portion is basically a string constant which you shove down the response pipe as fast as you possibly can. This can be a little tricky if you use a lot of middleware that sets cookies (these need to be set before sending http content), but in principle it's just flushing the response buffer, hopefully before jumping into some templating code (razor, php, etc) on the server. This may sound difficult, but then I'm just explaining it wrong, because it's near trivial. As you may have guessed, this static portion should contain all javascript inlined and minified. It would look something like

<!DOCTYPE html>
     <html>
         <head>
             <script>/*...inlined jquery, angular, your code*/</script>
             <style>/* ditto css */</style>
         </head>
         <body>
             <!-- inline all your templates, if applicable -->
             <script type='template-mime' id='1'></script>
             <script type='template-mime' id='2'></script>
             <script type='template-mime' id='3'></script>

Since it costs you next to nothing to send this portion down the wire, you can expect that the client will start receiving this somewhere around 5ms + latency after connecting to your server. Assuming the server is reasonably close this latency could be between 20ms to 60ms. Browsers will start processing this section as soon as they get it, and the processing time will normally dominate transfer time by factor 20 or more, which is now your amortized window for server-side processing of the <dynamic> portion.

It takes about 50ms for the browser (chrome, rest maybe 20% slower) to process inline jquery + signalr + angular + ng animate + ng touch + ng routes + lodash. That's pretty amazing in and of itself. Most web apps have less code than all those popular libraries put together, but let's say you have just as much, so we would win latency+100ms of processing on the client (this latency win comes from the second transfer chunk). By the time the second chunk arrives, we've processed all js code and templates and we can start executing dom transforms.

You may object that this method is orthogonal to the inlining concept, but it isn't. If you, instead of inlining, link to cdns or your own servers the browser would have to open another connection(s) and delay execution. Since this execution is basically free (as the server side is talking to the database) it must be clear that all of these jumps would cost more than doing no jumps at all. If there were a browser quirk that said external js executes faster we could measure which factor dominates. My measurements indicate that extra requests kill performance at this stage.

I work a lot with optimization of SPA apps. It's common for people to think that data volume is a big deal, while in truth latency, and execution often dominate. The minified libraries I listed add up to 300kb of data, and that's just 68 kb gzipped, or 200ms download on a 2mbit 3g/4g phone, which is exactly the latency it would take on the same phone to check IF it had the same data in its cache already, even if it was proxy cached, because the mobile latency tax (phone-to-tower-latency) still applies. Meanwhile, desktop connections that have lower first-hop latency typically have higher bandwidth anyway.

In short, right now (2014), it's best to inline all scripts, styles and templates.

EDIT (MAY 2016)

As JS applications continue to grow, and some of my payloads now stack up to 3+ megabytes of minified code, it's becoming obvious that at the very least common libraries should no longer be inlined.

2
  • I didn't get the which is now your amortized window for server-side processing of the <dynamic> portion part - The server processes what ever it needs and only then serves the entire rendered html (head+body), what other server processing is needed after that?
    – BornToCode
    Oct 29, 2015 at 11:37
  • @BornToCode The idea is to give client something to do at the same time the server side has something to do. Because the client libraries need to be interpreted - it's better to get that process started before doing any computation on the server. The amortized window is the time it takes the client to process the JS. You get that window for free, if you orchestrate a 2-stage rocket.
    – Gleno
    Nov 2, 2015 at 6:12
21

Externalizing javascript is one of the yahoo performance rules: http://developer.yahoo.com/performance/rules.html#external

While the hard-and-fast rule that you should always externalize scripts will generally be a good bet, in some cases you may want to inline some of the scripts and styles. You should however only inline things that you know will improve performance (because you've measured this).

2
  • 1
    I think Yahoo also recommend adding all the Javascript into one HTTP call too - this doesn't mean that the scripts should all be in the same file during development though Sep 26, 2008 at 11:59
  • 1
    Also, as noted above, HTTP/2 changes the "1 call" practice as well. May 16, 2018 at 23:00
14

i think the specific to one page, short script case is (only) defensible case for inline script

0
9

Actually, there's a pretty solid case to use inline javascript. If the js is small enough (one-liner), I tend to prefer the javascript inline because of two factors:

  • Locality. There's no need to navigate an external file to validate the behaviour of some javascript
  • AJAX. If you're refreshing some section of the page via AJAX, you may lose all of your DOM handlers (onclick, etc) for that section, depending on how you binded them. For example, using jQuery you can either use the live or delegate methods to circumvent this, but I find that if the js is small enough it is preferrable to just put it inline.
6

Another reason why you should always use external scripts is for easier transition to Content Security Policy (CSP). CSP defaults forbid all inline script, making your site more resistant to XSS attacks.

0
4

I would take a look at the required code and divide it into as many separate files as needed. Every js file would only hold one "logical set" of functions etc. eg. one file for all login related functions.

Then during site developement on each html page you only include those that are needed. When you go live with your site you can optimize by combining every js file a page needs into one file.

4

The only defense I can offer for inline javascipt is that when using strongly typed views with .net MVC you can refer to c# variables mid javascript which I've found useful.

3

On the point of keeping JavaScript external:

ASP.NET 3.5SP1 recently introduced functionality to create a Composite script resource (merge a bunch of js files into one). Another benefit to this is when Webserver compression is turned on, downloading one slightly larger file will have a better compression ratio then many smaller files (also less http overhead, roundtrip etc...). I guess this saves on the initial page load, then browser caching kicks in as mentioned above.

ASP.NET aside, this screencast explains the benefits in more detail: http://www.asp.net/learn/3.5-SP1/video-296.aspx

3

Three considerations:

  • How much code do you need (sometimes libraries are a first-class consumer)?
  • Specificity: is this code only functional in the context of this specific document or element?
  • Every code inside the document tends to make it longer and thus slower. Besides that SEO considerations make it obvious, that you minimize internal scripting ...
2

External scripts are also easier to debug using Firebug. I like to Unit Test my JavaScript and having it all external helps. I hate seeing JavaScript in PHP code and HTML it looks like a big mess to me.

2

Another hidden benefit of external scripts is that you can easily run them through a syntax checker like jslint. That can save you from a lot of heartbreaking, hard-to-find, IE6 bugs.

1

In your scenario it sounds like writing the external stuff in one file shared among the pages would be good for you. I agree with everything said above.

1

During early prototyping keep your code inline for the benefit of fast iteration, but be sure to make it all external by the time you reach production.

I'd even dare to say that if you can't place all your Javascript externally, then you have a bad design under your hands, and you should refactor your data and scripts

1

Google has included load times into it's page ranking measurements, if you inline a lot, it will take longer for the spiders to crawl thru your page, this may be influence your page ranking if you have to much included. in any case different strategies may have influence on your ranking.

1
  • Google lets scripts load before indexing.
    – Ken Sharp
    Dec 30, 2020 at 1:46
1

well I think that you should use inline when making single page websites as scripts will not need to be shared across multiple pages

0
0

Having internal JS pros: It's easier to manage & debug You can see what's happening

Internal JS cons: People can change it around, which really can annoy you.

external JS pros: no changing around you can look more professional (or at least that's what I think)

external JS cons: harder to manage its hard to know what's going on.

-3

Always try to use external Js as inline js is always difficult to maintain.

Moreover, it is professionally required that you use an external js since majority of the developers recommend using js externally.

I myself use external js.

1
  • 3
    Professionally required? Why? Who says that?
    – Siyah
    May 24, 2019 at 11:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.