惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

Mathias Bynens

A horrifying globalThis polyfill in universal JavaScript JavaScript engine fundamentals: optimizing prototypes JavaScript engine fundamentals: Shapes and Inline Caches Asynchronous stack traces: why await beats Promise#then() ECMAScript regular expressions are getting better! Unicode property escapes in JavaScript regular expressions ES2015 const is not about immutability Valid JavaScript variable names in ES2015 Unicode-aware regular expressions in ES2015 Dear Google, please fix plain text emails in Gmail PBKDF2+HMAC hash collisions explained JavaScript has a Unicode problem Processing Content Security Policy violation reports Hiding JSON-formatted data in the DOM with CSP enabled Loading JSON-formatted data with Ajax and xhr.responseType='json' Reserved keywords in JavaScript How to support full Unicode in MySQL databases How to speedrun Dropbox’s Dropquest 2012 Unquoted font family names in CSS Unquoted property names / object keys in JavaScript Valid JavaScript variable names in ES5 CSS character escape sequences JavaScript’s internal character encoding: UCS-2 or UTF-16? The smallest possible valid (X)HTML documents JavaScript character escape sequences JavaScript foo.prototype.bar notation Ambiguous ampersands HTML element + attribute notation How I detect and use localStorage: a simple JavaScript pattern Unquoted attribute values in HTML and CSS/JS selectors The end-tag open (ETAGO) delimiter Using the oninput event handler with onkeyup/onkeydown as its fallback Everything you always wanted to know about touch icons In defense of CSS hacks — introducing “safe CSS hacks” AirPlay video support in iOS Safari — a bookmarklet Completing Dropbox’s Dropquest 2011 in 60 seconds Using CSS without HTML How to create simple Mac apps from shell scripts Using setTimeout to speed up window.onload Bulletproof JavaScript benchmarks Thoughts on Safari Reader’s generated HTML How to enable Safari Reader on your site? The XML serialization of HTML5, aka ‘XHTML5’ The id attribute got more classy in HTML5 The three levels of HTML5 usage The HTML5 document.head DOM tree accessor Bulletproof HTML5 <details> fallback using jQuery Displaying hidden elements like <head> using CSS Using Showdown/PageDown with and without jQuery
Inline <script> and <style> vs. external .js and .css — what’s the size threshold?
Mathias · 2010-04-11 · via Mathias Bynens

Inline <script> and <style> vs. external .js and .css — what’s the size threshold?

Published · tagged with CSS, HTML, JavaScript, performance

When is it acceptable to use inline <script> elements? When is it better to use separate .js files? The same question can be asked about inline vs. linked CSS — where do you draw the line?

I had been pondering about this for a while, but while writing my post about optimizing the asynchronous Google Analytics snippet I was reminded I didn’t have a solid answer to my question yet. Is it worth it to separate the Analytics snippet into a separate .js file, so it can be cached? Or would that be a bad idea, considering the additional HTTP request needed to retrieve just a few hundred bytes of data?

Obviously, I wasn’t gonna figure it out by myself. So I decided to ask Kyle Simpson, creator of LABjs; and Billy Hoffman, of Zoompf fame. (Thanks, guys!)

Here’s what Kyle said (emphasis mine):

I’d say the threshold for me on ‘size’ would be around 400–600 bytes, or approximately 6–8 lines of JavaScript code. Generally speaking if something is less than ½ KB, it’s not worth being in its own file, nor is it worth the HTTP overhead (even factoring in caching). This opinion takes into account the following things:

1. HTTP request overhead size is roughly 500-700 bytes on average (including request and response headers — but not including cookies!). So, if I’m spending more bytes of transmission to get content than the content itself, that’s probably a bad sign.

2. A non-trivial amount (don’t know the exact statistics, but probably roughly 3–5%) of users have no (or practically none) caching ability at all. This is even more true when you consider really small caches like those found on mobile phones. So, in those cases, a separate file request for the sake of caching is completely lost on them. They are paying the ‘penalty’ of loading that file every time. And for mobile users especially, this is bad because they also are generally on slower/less reliable connections, so the impact can be doubly negative.

3. Many people suggest combining all local .js files into one file as a way to address the HTTP overhead issue. In general, reducing HTTP requests is good, but going all the way down to one file may not be optimal. Consider loading and caching behavior with a single big file that has a dozen other files concatenated together in it. Firstly, the single bigger file will load slower since it loads byte-by-byte serially than if say two files, each half the size, were loaded in parallel. Secondly, a big concatenated file is more likely to have changes more frequently, which means that if even one character of that big file changes, every single user now has to re-download the entire file with lots of unchanged (and now unfortunately uncached) content wasting bandwidth/time.

So, since the ga.js loading/initialization code should pretty much never change, you would want to make sure that you combine it with other local script code that also doesn’t change very often — for instance, if you have a stable library file that only changes once every 3–6 months, this would be a better file to tack the code onto than say a file that has experimental or user-experience oriented script logic in it that might change frequently as you tweak your site’s content.

Billy raised some interesting points as well (again, emphasis mine):

The first thing to keep in mind is we are talking about approximately 320 bytes. The choice is should we include this 320 bytes in every HTML page, or place them in a JavaScript file that will get cached.

The main benefit to the async snippet is to not block the browser when downloading the ga.js file. According to Builtwith.com, so many sites are using GA that it is almost certain a cached copy of ga.js already exists on the machine so this blocking is hardly ever a big deal. The only other real benefit is that maybe you’ll be able to register a hit even if the user doesn’t fully load the page because you can put the async snippet at the top.

Making an HTTP requests costs roughly 100 ms (the average TTFB I’ve seen, though it can be as low as 50 ms or 60 ms). Let’s say 100 ms. Let’s also say someone has a low powered DSL connection, say 786 kilobits per second. Thats means they can download 786 * 1024 / 8 = 100,608 bytes a second, or roughly 10 kilobytes every 100 ms. Someone would have to visit approximately 32 pages on your website for the overhead of them downloading that 320 bytes of the GA snippet over and over again to equal 100 ms, the amount of time to fetch the snippet in a JS file.

So if you don’t have any external JS files already, creating one just for the GA snippet is silly and not worth it. However, if you already have a JS file, and you are loading it async using LabJS or something, then including it could help you. Of course, at the end of the day, we are talking about 320 bytes ;)

Update (December 2011): Guy Podjarny wrote an interesting article on this, in which he concludes that “[t]he HTTP overhead of a request & response is often ~1 KB, so files smaller than that should definitely be inlined” and also that “testing shows you should almost never inline files bigger than 4 KB”.

Conclusion

It’s probably a good idea to place small code snippets of just a few hundred bytes inline in the document, unless you’re using separate files for scripting or CSS anyway. In that case, it’s better to just merge the code in there, since the ratio of bytes lost in making the HTTP request vs. file size is much smaller compared to creating a separate file just for the tiny snippet.

Leave a comment

Comment on “Inline <script> and <style> vs. external .js and .css — what’s the size threshold?”

Name *

Email *

Website

Your input will be parsed as Markdown.

Spammer? (Enter ‘no’) *