when should i use inline vs external javascript

when should i use inline vs external javascript  using -'javascript,html,performance,frontend'

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?


asked Sep 22, 2015 by android_master
0 votes

15 Answers

0 votes

The rule is 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.

answered Sep 22, 2015 by akhilesh
0 votes

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).

answered Sep 22, 2015 by thiru
0 votes

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.

answered Sep 22, 2015 by deven.bendale
0 votes

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 and phases, but think of them instead as and . 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


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 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.

answered Sep 22, 2015 by virendra.bajaj
0 votes

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.
answered Sep 22, 2015 by maurya
0 votes

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.

answered Sep 22, 2015 by santosh soni
0 votes

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

answered Sep 22, 2015 by yogeshplv
0 votes

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.

answered Sep 22, 2015 by pradip.bhoge
0 votes

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.

answered Sep 22, 2015 by devkumargupta
0 votes

Three considerations:

  • How much code do you need (sometimes libraries is a first-class consumer !-)
  • Specifity (is this code only functional in the context of this specific document or even element)
  • Every code inside the document tends to make it longer and thus slower. Besides that SEO considerations makes it obvious, that you minimize internal scripting ...
answered Sep 22, 2015 by dhananjayksharma
0 votes

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

answered Sep 22, 2015 by rajeshujade
0 votes

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.

answered Sep 22, 2015 by suyesh.lokhande
0 votes

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.

answered Sep 22, 2015 by mtabakade
0 votes

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.

answered Sep 22, 2015 by suyesh.lokhande
0 votes

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.

answered Sep 22, 2015 by bhavin