The Cost of JavaScript in 2019
v8.dev
v8.dev
We do not grow organically by people stumbling on our app and thinking "wow that was fast". We go through months of enterprise sales process to ink a deal, then onboard maybe 20 key users at the company.
To put the effort into code splitting would be purely an exercise in keeping up with the new hotness. That's not to say we don't keep a close eye on the package size, just that it's not much of a great optimization for a regular user's experience in our case.
Also serving all assets from the same domain saved us some time in domain resolution.
As long as your service uses HTTP/2 it's far more efficient from DNS and multiplexing/TCP/TLS handshake standpoint to serve from your own domain. And better for security most of the time since hardly anyone uses CSP and hash signatures for their third party scripts.
The original sell of CDN was that everybody would have the same libraries cached. With the massive poliferation of JS you would have to have a 100 gig cache for that to be remotely true.
A couple years back I moved a C# app to .NET core for the HTTP/2 support. I tried removing the ~4 external CDN dependencies just to see what happened. Load speed improved around 30% because no additional DNS lookups and TCP window stuff worked around by multiplexing.
An aside, try not to use multiple subdomains. They trigger DNS lookups and don't work as well with CORS. It's easy to accidentally trigger cors and a bunch of meaningless round trips by using different subdomains
(I work with many IR Top 100 retailers, and I’ve helped to build the dashboards comparing edge vs origin. It’s valuable even for sites where the majority of the visitors are in the US, and especially so if you have a substantial international audience)
But that implies: You allow a CDN to host your initial asset, possibly a security risk
You only use that one CDN for most/all non-dynamic content.
When latency becomes that important I would rather host my own AS. Giving CDN the origin and your first content load is effectively handing off your entire site security to a third party.
At that scale you could easily and cheaply run multi-homing on your own AS in maybe 10 colos across the world. Maybe 100k a year to eliminate third party risk. Maybe worth it? I think so
HTTP/2 is not always faster depending on if your link connection has any loss to it (wifi, spotty 4g).
We came to the same conclusion when investigating as well, but because of the structure of our site - we had just a handful of layout primitives that were reused across the site so page splitting had no benefits because every page used the same code anyway.
Still an optimisation to look into if you can benefit from it!
JavaScript vms got so much faster than 10 years ago and yet all the web sites are much worse. Memory and cpu hogs.
This is not something improving the vm can fix. There just is no competition so that customers could send a feedback signal saying that performance is unacceptable.
For user-facing applications performance only really matters in human time, and is pretty far down on the list of how people choose software over things like features, price, ease of use, etc.. Until performance becomes a big problem because the app/site becomes unusable it's basically no problem.
Hackers might not like it but we're such a weird market to sell to. Not necessarily that performance is a weird preference but that by in large hackers are perfectly fine with woefully inefficient feature-packed apps for their "primary" apps like their IDE but then want super lightweight skeleton-featured experiences for everything secondary.
well, even the most feature-bloated IDE loads faster than GMail on my computer (before anyone asks, I'm on gigabit fiber)
There was a study that has shown correlation between revenue drop and milliseconds that page takes to load. It’s not only hackers that respond to performance.
As for competition - due to network effects there are very few competitors to things like Facebook, Amazon and other big tech.
If these were federated services participating in communication built around some gigantic independent social graph - that would enable more competition in terms of UI performance, features, etc. Not going to happen anytime soon though.
It may be a controversial opinion, but I think part of the problem today is that young web developers look to people who work at high-profile places like Facebook and Google as role models and for examples of best practice. And yet, a lot of Google's and Facebook's own web properties are... less than exemplary... in terms of performance, usability, design, and other factors that are important in most situations, and have been getting steadily worse rather than better over time. I humbly submit that the reasons for the runaway success of these giants have really very little to do with the quality of their sites any more, and that up to a point they can get away with things because of their dominant positions and lock-in effects that simply wouldn't be acceptable for most of the rest of us.
Now a future programmer three years later tells the business manager that they can do this much better now for $x. It will improve nothing as far as the user in concerned. Maybe the page will load faster but the user may not even notice. Maybe they will save some money on hosting and bandwidth costs.
In most cases, the business person will most likely tell the programmer to keep working on to new feature z2021 project and leave the old code alone. This is until there is a security problem or the old code effects the z2021 project.
(Spoiler alert: If your system is well-enough implemented to be correct, it is well on the way to being secure and performant too)
I’m not sure if those were peak UI performance. It wouldn’t surprise me.
I’m guessing at least a generation of people haven’t actually experienced reasonably responsive computing environments.
We are fast approaching a time when hardware will not be able to save us so I believe we'll eventually see devs have to slow down and optimize better.
There are times that I perceive the community trying to convince itself that web devs can have their cake and eat it too. That it's not just possible but easier to built performant, accessible and maintainable apps in React/Angular/Vue, when that's just not a universal truth. Sure, those tools may make certain aspects of development easier through the abstractions they leverage, but those also come with a cost (i.e. breaking API changes seem to be in vogue these days).
Ultimately, this part in parcel of the JS community. Aspects of the ecosystem feel so fragile (NPM, framework/lib churn, etc.) that it's easy to be cynical about web app performance.
And the implicit response is that people using available resources for whatever they want is fundamentally a good thing.
> This is not something improving the vm can fix. There just is no competition so that customers could send a feedback signal saying that performance is unacceptable.
I think that's part of the reason Google made AMP: they don't allow arbitrary JavaScript scripts because it's not practical to get all websites and all developers to optimise JavaScript usage. Likewise, the amount of CSS code allowed is strictly limited.
Google tells me the code to add to my page (for G+, advertising, analytics), then things like Google Lighthouse tell me don't do X, Y, Z that are all done by the code Google told me to use.
Minimise request size, leverage browser caching, defer parsing, ... they don't even minify? At least they enable gzip, Amazon ads don't even do that.
Load show_ads.js asynchronously ... well why not tell me to do that up front rather than after the fact in PageSpeed?
Google is a huge company and not every team has the same priorities is the most likely answer. It's not realistic to expect they're going to optimise the loading speed of literally everything they release.
Web best practice checks will always have some degree of false positives as well as websites are so complex.
I wrote my own Chrome extension that checks websites for best practices (https://www.checkbot.io) and had to weigh up how generally useful a test was compared to its typical false positives rate. The website for the product does pass the vast majority of the tests though, but I've only got a single website to manage compared to Google.
> Eg: https://gtmetrix.com/reports/alicious.com/RyJ575Jd
By the way, isn't some of this advice outddated?
"This page has 25 external Javascript scripts. Try combining them into one."
"This page has 3 external stylesheets. Try combining them into one."
This is obsolete with HTTP/2 because files can be downloaded in parallel. Combining the files will also increase the weight of pages that don't need every file.
How about just the things that get duplicated on more than 10Million websites?
>By the way, isn't some of this advice outddated? //
Yes, the link was just supposed to be broadly indicative. Google signpost Lighthouse as the primary tool now rather than PageSpeed I think but you can't link to that on the web. [And even Lighthouse has false positives, but that's not the issue here.]
Some things were not even possible and were "unlocked" by browser optimizations.
For example: writing games or complex animations with JS and the DOM was nearly impossible (that gap was filled with flash). As browsers got faster, the need for flash just went away.
Also the more APIs the browsers ship, the more is possible to do with JS, and so the pages ship more JS to use these new featuers. [1]
For example: after browser notifications became broadly available, almost _all_ pages ship now a snippet of JS code to annoy the user with notifications. I'm sure such fads blow up the average size of bundled JS across all web pages.
[1] Look at this! https://developer.mozilla.org/en-US/docs/Web/API
- no declarative APIs for DOM updates
- no good APIs to do batch updates
- no native DOM diffing (so decisions on what to re-render have to be done in userland)
- no DOM lifecycle methods and hooks (you want to animate something before it’s removed from DOM, good luck)
- no built-in message queueing
- no built-in push and pull database/key-value store with sensible APIs (something akin to Datascript)
- no built-in observables and/or streaming
- no standard library to speak of
- no complex multi-layered layout which matters for things like animations (when animating a div doesn’t screw up the whole layout for the entire app/page)
etc. etc. etc.
As a result every single page/app has to carry around the whole world just to be barely useable.
How long have they been debating the Observable proposal? 4-5 years?
That said, does a native observable actually buy that much performance-wise? If not, then perhaps an addon library is better. Once a library makes it into JS, it is there forever. That's a big risk when decent libraries already exist.
I don't know, but it should.
And all this while some other HNers are saying that the browsers are too complicated and its so sad that there won't ever be completely new independent browsers... :)
So pages before this javascript bloat became commonly accepted were unusable? Maybe at some point web developers have to accept that the web was simply not built for the things they're trying to do with it, and that comes with a cost. Maybe they should evaluating whether they _really_ need animations on everything, whether everything _has_ to be a SPA made in [current popular framework]. I'm not even saying these things are bad, they absolutely do have value, but that value has a tradeoff, and usually that tradeoff is placed on your customers.
If every JS page in the world today includes the same line of code, isn’t it obviously the fault of browser makers for not making that line of code part of the JS prelude and thereby making it “free”?
And more features = more surface area for bugs.
1. Turning the browser into an OS (what Google is working toward)
2. Downloading an OS on each page load (What webassembly is working toward)
All the dilly-dallying results in community efforts that pile on top of each other to create all this bloat that is carried from one tool to the next framework.
So what's your proposal? To have one browser for "web documents" and another just for those things built by web developers that you dismiss with straw men, yet still acknowledge as having value?
If they have value, but they incur a cost, shouldn't we be looking at why we have that cost and how to drive it down? That's exactly what the post you're replying to is trying to convey.
Yes, not everything has to be animated or an SPA, because some things are good enough as just simple "web documents". But others gain in usefulness, usability and cognition by being augmented (e.g. data visualisation, business apps, games, et al). Not every web content is created for the same purpose. We still end up with the same crippled DOM/JavaScript combo. That should be the focus of the conversation.
They weren't unusable. They, too, were barely useable in any scenario outside of a static HTML page with static images. There's a reason why jQuery was (and probably still is) the most popular Javascript library. You don't have to go too far to see what people were doing before "js bloat", just look at ExtJS [1]. They would have loved to have the "js bloat" 10 years ago.
That directly of course doesn't help with bundle sizes, but it means bundles don't have to carry so much logic and optimizations because they can just use the already performant APIs.
A “disappearing” animation is an embellishment and a purely visual effect; therefore, it only depends on what the original object looked like, not the entire original object itself.
It is a lot simpler to reason about the state of your system if you delete items immediately and create proxies to handle special effects for deletion.
For example, to have an element “animate away”: create a new purely-visual element at an absolute location that looks like the original object, delete the original object immediately, and then let the proxy go away whenever it is done animating. This completely frees you from having to worry about the true lifetime of the original object.
The OPs point is that doing this is far more DOM-intensive, and leads to worse performance. It isn't a good solution.
Yeah, and to properly do that you need that very same JS bloat to:
- somehow observe a DOM element being destroyed (there are no lifecycle methods on DOM objects)
- somehow figure out if it's the object being destroyed, or it's parent, or grandparent, or...
- somehow quickly create a visual proxy instead of the object being destroyed, quickly substitute it in the DOM (avoiding repaints, reflows and jank). With all the correct things for it: size, position, scroll position, all internal representation (let's say we're animating a login form floding in on itself)
- somehow animate that proxy object
- and then remove that proxy object.
It's a lot simpler
By the way. If I remember correctly, just getting the position of an object causes a full-page reflow [1]
As an example look at Svelte. It compiles down to super efficient imperative code without sacrificing the dev experience. A hello world weights like 5kB gzipped I believe.
All of the other frameworks seems so convoluted and to me it looks like people are reinventing the wheel left and right.
Inline scripts prevent using CSP 'unsafe-inline' therefore increasing XSS risk. Performance is only a secondary problem here.
When working with external files a programmer almost has to work with the framework, and once (s)he does that the framework - well, a modern framework - would take care of the security details and do it right.
When working inline it's too easy to add a script tag manually, and from there it's a bit too easy for someone in the team to miss something (write a js without the hash/nonce and not notice the warning) or talk him/herself down to lowering security ("importing this 3rd party js is too hard, lets use just a nonce and forget about hashes", "this policy is too constraining, it's just a SMALL script, no risk here").
When working in a team, it's much better to have a hard and fast rule which forces everyone to work right. There's really no reason to use inline when using external files works really well now - and is apparently better for responsiveness too.
Note however that there are interactions between using a nonce and caching which require caution (since nonce is supposed to be used only once but caching can work against that), so proper protection here has a cost in complexity and/or speed.
If one takes out the personal pronoun, the comment is still snarky, which breaks the site guideline "Don't be snarky."
(I think I know the answer, but even so I'm interested in what other people think.)
- It's very easy to find JS programmers. There's a _lot_ of them. But programmers proficient with pure functional programming languages are harder to come by.
- JS is natively supported by browsers and it is pretty much guaranteed that the code you write is going to work for ever. Elm on the other side, who knows? It might lose steam and go into support mode, or drop support, or maybe they introduce breaking changes in a future version. JS is a much safer bet.
- Writing Elm does not guarantee a good polished product. You can write bad software in good languages and vice-versa.
That being said, it's only a risk. Maybe your team is more comfortable with Elm and they get more productive. Maybe the language design makes easier writing code with less defects. Maybe it actually gives you an edge.
It is hard to say if Elm brings value to your business. It most likely depends on what kind of a business that is (web agency than cranks 3 visit-card websites a day? Or is it one developing a complex app?)
In any case, managers get very nervous about languages that are not mainstream. And they do have good reasons.
> But programmers proficient with pure functional programming languages are harder to come by.
I used to get a similar argument when pushing Python over Java, and my counterargument is the same: I wouldn't hire a JS programmer who was afraid or unwilling or unable to learn Elm. I would bet that any normal person smart enough to solve Sudoku problems could learn Elm, I wouldn't make that bet with JS/CSS/HTML.
> It might lose steam and go into support mode, or drop support, or maybe they introduce breaking changes in a future version. JS is a much safer bet.
But who is using just JS these days? Frameworks and transpiling are the order of the day, no? Same argument applies to them. And JS is a moving target too. As for "breaking changes", well, it is just version 0.19 so far. Once they hit 1.0 I would bet on Elm being more stable than JS+Whatever.
Weigh this against zero front end bugs. That's a staggering (if hard-to-quantify) cost savings.
> Writing Elm does not guarantee a good polished product. You can write bad software in good languages and vice-versa.
Yeah but that's not an argument in favor or against any particular language, and in the specific case of JS vs Elm I think it's clear Elm wins. If your developers are truly crap then, yeah, Elm won't save them. But then you also have bigger problems than what tech stack to use, eh?
Would you hire an Elm programmer who was afraid or unwilling to learn proper JS?
If you started with Elm then JS/CSS/HTML+Frameworks|Transpiled-langs et. al. would, I imagine, seem like a massive amount of stuff to learn, eh?
I think the Elm-first programmer would be right to ask, "What's the payoff? What awesome new powers do I gain, impossible with Elm, as reward for all this blood sweat and tears?"
(Elm is wildly easier to debug than the status quo stuff. The compiler is awesome for that. So the hypothetical Elm-first programmer has to learn not just the status quo stack but also how to debug it!)
So, again, it seems to me like it behooves the cost-conscious programmer to carefully examine the cost/benefit ratio of non-Elm-implementable features in light of the availability of Elm.
I am presupposing, like I said above, that you can take pretty much any member of the Sudoku-solving public and train them up in Elm in a few weeks. Even paying them at parity with JS devs, the time and effort savings of Elm vs. JS et. al. would be substantial, I believe.
(Personally, I would want at least two or three people on the team who knew what was going on under the hood.)
What I'd look for is an open, sharp mind. Willing and happy to learn new things and paradigms, even those that go beyond their comfort zones, whether it is JS, Elm or Java. Someone to whom programming languages, frameworks and libraries are just TOOLS to accomplish a certain goal, and not part of their identity.
I'm willing and happy to learn new tools. I'm happy with hiking in flip-flops if that's all that's available, but I'd certainly choose hiking boots if given the choice. I suspect most "good" developers have the same attitude.
We are discussing the flipside of that: looking for an employee/teammate. And I agree, a company that uses better tools is always more attractive.
> would prefer the Elm one. I've never written a line of Elm before
If you've never written a line in it before,how did you decide that its a better tool?
That's not exactly the spirit of what I meant, but, yes.
> That just sounds like good old fashioned tribalism
I can't really control what it sounds like to you, can I?
My whole point is that Elm is (or one day soon will be) much superior to JS et. al. This is a cost/benefit analysis, not tribalism. (I'm not an Elm fanboy. I don't actually like it that much, in fact.)
It's puzzling that more JS programmers don't adopt Elm.
It's reasonable for an Elm developer to ignore JS to the extent possible.
That's the point of Elm, eh?
> What I'd look for is an open, sharp mind. Willing and happy to learn new things and paradigms, even those that go beyond their comfort zones, whether it is JS, Elm or Java. Someone to whom programming languages, frameworks and libraries are just TOOLS to accomplish a certain goal, and not part of their identity.
Sure! Me too. But now I can make the scarcity argument, no? And you've got to pay those folks well, eh?
I'm postulating that you can take normal people (smart enough to solve Sudoku) and have them productive in Elm within a month or so. You probably would not have to pay them as much as an equivalently-productive JS programmer, and certainly not as much as the kind of person you described.
Again, I'm talking about the business value of a given software production tool not the entertainment value or the personal-growth value for the devs.
I'm sorry, but your enthusiasm for Elm might be blinding your reasoning. JS is an EXTREMELY flexible languange. Open and malleble to both experts and newbies alike. Open to all styles and paradgims of programming including object and functional, which is what makes it possible to be the worlds most compiled to languange (https://github.com/jashkenas/coffeescript/wiki/List-of-langu...). Elm comes nowhere close to beating the JS cost benefit analysis.
In the end, the business value always wins out. Elm, started in 2012 is even older than react, and would've took of long ago if it had any business value.
> It's puzzling that more JS programmers don't adopt Elm.
JS developers come from diverse backgrounds (expert, newbie, functional, object, procedural etc). The ones that like elms approach will adopt it, those that don't will use a different style/compiler/transpiler; and it all ends up as JS. That's flexibility at work.
As I said, I'm not an Elm fanboy. I don't actually like it that much.
> JS is an EXTREMELY flexible languange. Open and malleble to both experts and newbies alike. Open to all styles and paradgims of programming including object and functional
Sure. So what? So is LISP. I'm talking about "business value", meaning: if you don't care about how shiny and flexible and open your programmers' languages are, you care about the hard $$$ cost of development and maintainence per unit of webapp functionality delivered, then Elm makes a heck of a lot more sense than JS+etc.
The compiler and the fact that you get zero front-end errors just blows away the typical JS dev cycle with a buggy front-end. I can't quantify it because you can't quantify the hypothetical lost business due to hypothetical bugs that don't happen because you're not using JS.
To me it seems clear that it is much cheaper to develop and maintain Elm apps.
> what makes it possible to be the worlds most compiled to languange
Nah. That's because it's the only language in the browser and people would rather use something else.
> Elm, started in 2012 is even older than react, and would've took of long ago if it had any business value.
You're begging the question I think, my whole puzzlement is that the business value seems very clear yet Elm hasn't taken off.
To date, the only serious objection I've heard here and elsewhere is that they removed older docs when they bumped a minor version number. That sucks.
It doesn't, sorry. JS resources, developers and libraries are atleast x1000 more than Elm. business is about supply and demand, more supply == cheaper cost. That's business 101. That's why there are hardly any Elm jobs advertised if compared to JS. You keep talking about how Elm makes better business sense, but the reality of it is completely different. Maybe all those employees are just making the wrong business decision, right? Wishful fanboy thinking. You are even in denial about liking Elm, which is pretty obvious to anyone reading your comments about it.
> Nah. That's because it's the only language in the browser and people would rather use something else.
Something else like dart, flash, VB, Java... oh wait! They've all been used in the browser before, none passed the test of time. And Elms approach (transpiling to JS, CSS, HTML) is not unique either, e.g. TypeScript and its not exactly shinning against competition in its league either. Once it beats competition there, then maybe it can start taking aim at JS, CSS and HTML.
> You're begging the question I think, my whole puzzlement is that the business value seems very clear yet Elm hasn't taken off.
It seems very clear to you, because you like and have invested in the language so much. A less invested "business person" will have a more objective view of which of the two (JS vs Elm) makes more business sense.
Let this be a lesson to me.
"Answer not a fool according to his folly, lest thou also be like unto him."
(I don't even use Elm. Sheesh.)
Okay now that's just ridiculous.
There are no other native scripting languages that the browsers understand. Of course it's going to be the most compiled to language, doh.
Your statement is along the lines of "all Earth life breathes oxygen, this has to mean something".
Well of course it means something. It means that our planet doesn't offer alternative biomes. It doesn't mean that oxygen-based life is ideal (which it isn't).
JS is a legacy everybody is stuck with. That doesn't make it good. It only makes it a safe choice because it's widely used and has a larger pool of programmers as you said.
Most businesses are followers. If an universally better technology makes strides you can be damn sure a lot of those follower businesses will be all over it after Facebook or Google adopts it. Nothing new, businesses always seemed to operate like so.
Not sure what value do your comments bring except for stubbornly reasserting the state of our currently (and highly suboptimal) reality. Practically almost every non-junior programmer knows how we arrived here.
And finally, the better business value of JS [devs] is far from given. It's a local maximum and nothing else. I've seen teams replace 5 average programmers with 1 senior, save 40% expense in doing so, and have much more maintenable code with much less support costs. These things do happen even if they are not the majority. And they will keep happening until one day somebody like you will lecture people how "JS was never bound to succeed".
You should realise you are only reasserting current reality and are doing post-hoc rationalisations in an attempt to understand the said reality. This is completely fine; we all try to make sense of the world. Reality however is always in flux. Keep an eye out. ;)
Yes. If it compiles, it works.
> Impossible.
No.
When I was evaluating Elm it was my favorite choice out of all the various strongly typed flavors of javascript, clean syntax, good abstractions, and very strong runtime guarantees. The thing that made us reject it, and will keep me from recommending it to others, was the change made, I believe in version 0.15 which, as I understand it, restricted FFIs so that only core maintainers could write them. I know several companies have frozen their version of Elm due to the change.
Particularly when working with external packages written in JS, not having an escape hatch is a huge vulnerability. We've already hit one instance since using Reason where if we could not drop down into pure JS we would have had to either rewrite one of our main dependencies or at least hard-fork it and re-write substantial portions of the application, a multi-month (maybe multi-year) slowdown that would have killed the project.
At this point I would not recommend Elm to anyone who is not willing to rewrite any pure javascript module they might want to use (this may fit the bill at some very large corporations).
https://guide.elm-lang.org/interop/
> But what happens when you need to do something in JavaScript? Maybe there is a JavaScript library you absolutely need? Maybe you want to embed Elm in an existing JavaScript application? Etc. This chapter will outline all the available options: flags, ports, and custom elements.
I haven't looked at it in depth yet.
The upside to this is that because ports work by message passing, it means that all the language's guarantees can be held even when using them, and packages can't do anything without you knowing about it.
The downside is it is a lot more verbose and awkward. In my opinion, it also makes community contribution to the standard library a lot harder.
Compared to that, React took me a day to get comfortable with. There is an argument to be made though, that behind that day there's potentially all those years of working with imperative languages which just isn't there for Elm.
The (B?)DFL pushes that even though it's not hit a 1.x version that it's production ready and stable, in our experience that isn't the case :(
Were they at least on Wayback Machine?
Also, the "LONG TASKS MONOPOLIZE THE MAIN THREAD. BREAK 'EM UP!" section header felt a bit on the nose.
+1. After seeing some opinions that Chrome is becoming the new IE over the past few weeks, I've switched to Firefox to do my small part in trying to prevent another browser monopoly.
also amusing seeing it come from Google.
I read C# documentation several times a week. I do not like it.
While I can't ever remember reading some documentation and saying, "Wow, that was fun!", so I can't say there's any documentation I like. But I do find that the MSDN documentation usually gets me working, and not reading documentation much faster than others for e.g. Python, Java, JavaScript, CSS, my pedometer.
MDN (Mozilla documentation for web stuff) is generally pretty good. Obnoxious colors aside, this javascript library is very easy to get started with:
Whereas with C# or Java or Ruby or Python or countless other languages the standard library is big enough that a quick search, find an example and boom I'm done (I always thought the MSDN was amazing; it's like Mozilla's JS documentation but for C# with tons of awesome examples). If it's highly complex I can find a library that likely depends mostly on standard library functions and not have to worry about tons of dependencies.
I do a ton of development in JS and I think its standard library is one of its biggest flaws. ECMA would rather avoid adding too much to it as they seem to view the language as a small, scripting language and the platform should provide everything. That's a valid view, I think, but I don't agree with it at all. It's grown far too much to keep that view IMO.
const data = { foo: 42, bar: 1337 }; //
>>> can be represented in JSON-stringified form, and then JSON-parsed at runtime: const data = JSON.parse('{"foo":42,"bar":1337}'); //
>>> As long as the JSON string is only evaluated once, the JSON.parse approach is much faster compared to the JavaScript object literal, especially for cold loads.For anything large enough to matter, I think you'd want to deliver it as an application/json blob, anyway. Or use protobuf.
There, the language parsing penalty is paid during the compile step, and as far as a user is concerned the object approach is obviously faster than parsing from JSON.
This does leave me wandering - is the result here applicable to other scripting languages too? The argument in the article would seem to apply in the general case, but perhaps other languages have some particularities that change the result.
They don't say how large but clearly it's not going to be better for a 2 keys object like in the example.
- What about other browsers?
- how big does it have to be to have a meaningful effect? I've seen an example out there with someone demonstrating amazing gains... on their 163KB of initial state. That's not typical. Or at least I really hope it isn't.
I wonder how many such tweaks it would take it to be worthwhile for companies to add it as a build step
This particular hack is absolutely nothing you have to worry about, just like esoteric performance tweaks available in any language stack. Write the JS you need and use it. Then profile and optimize as necessary.
It just seems like a human nature to paper over.
It’s an evolution.
Also micro performance becomes macro at scale. This is not something that you worry or think about with a handful of literals. It would be good for an inner loop or code generator.
We already established it's far slower parsing js; in most cases JSON parsing would fail - IIRC - on the first character ^[^{] ... so would it be worth being slower by the time it takes to check the first character, and then only JavaScript that started with { would be slower. Which I guess is virtually none.
I suppose those sorts of questions are part of what makes language design interesting.
And the reason it can't be as fast as a JSON parse is explained in the article: The grammar of JSON is much simpler. The literal parser in normal JS needs to deal with things like:
const data = { foo: /* something*/ 42, [barRef]: 1337 };
so needs to do more branching than a JSON parser. And yes, you can pre-scan the string to make sure it's not doing anything like that... but that probably already costs more than the tokenizer phase of a JSON parse, and it's overhead you still need to do that a JSON parse doesn't have to do.(note caveats/questions at the end of the article)
A tweet was going around that this change lead to a 30% increase in time-to-interactive.
If you're dumping Redux state from the server onto the page, you could benefit from it, and it's really only one place so its not actually making your overall code "dramatically worse".
Might be worth investigating if you have a ton of JSON.
Apparently this is faster than running the whole string through the full JS parser that has has to deal with all kinds of portential shenanigans in that block like references to variables instead of literals etc.
(Per the article’s advice, unless I’m missing something)
Oh... we are using Servlet 3.0
One of the places this helps you is when you push out a one line javascript bug fix without invalidating your CSS caching across the entire site, because the CSS files are identical.
It also helps you with people with the website open when the new code gets pushed. They either have all the old code or all the new code and no bizarre mishmash of the two.
It's a bit of a optimization as to be 100% sure users always get the latest files the version naming scheme is needed, but most of the time it will work anyway, eg. if you have no caching layers /CDN etc in-front of the web server. So if you want to shave off milliseconds on first load, go with the bundle, but if you want to save user's bandwidth and make your site/app more lightweight - don't bundle!
I don't want to "GET NEW REDDIT" as I'm urged to in the top left of every page because I don't want a card-based layout. The whole reason I and so many others left Digg for Reddit to begin with was for a highly skimmable, information-dense site!
Similarly, I don't want to install a mobile app. The page worked fine on mobile when I got my first iPod Touch a decade ago. Why do I have to see a huge USE APP button in the nav bar and then lose another 20% of the page at the bottom to a See Reddit In section at the bottom that's also urging me to install a native app?
Infinite scroll actually slows down my browsing experience too, since it no longer loads as many entries at a time and I have to keep waiting for pagination.
old.reddit.com
or for mobile
reddit.com/.compact
Both are low nuissance and both still work for me, although I am not sure if that is region based.
> reddit.com/.compact
I didn't know about that option. Bookmarked. Thanks for sharing!
It doesn't put a big red "GET NEW REDDIT" in the upper left that does a single-click update of your account settings? What region are you in?
> reddit.com/.compact
I just tried that and the top 40% of my screen was spent on a banner telling me, "You've been invited to try out Reddit's new mobile website!" Clicking that lead me to a page where both the top bar and the bottom section harass me to install their mobile app.
Desktop site [x]
Fast, reliable and well designed. I really enjoy using it.
How do you implement infinite scroll without JavaScript?
The theme tying all their choices together is costs they're willing to inflict upon their users. Bloated JS payloads are simply one example.
Technically it's possible.
Render the website server side as an image. Chrome 75+ supports native lazy loading of images, so a series of them stacked vertically is needed. Each image represents a new page, scroll through them to navigate. Click detection can be done with a <map> tag.
I wish Reddit ran something like Youtube Premium, a paid ad-free experience with actually comfortable layout.
I don't have any specific plans about opening the registration up yet, but you (or anyone else) can just email me for an invite. It's not intended to be difficult to get one, I just want to keep the site's growth under control.
The address to email (and a lot more info about the site's goals) are in the announcement post: https://blog.tildes.net/announcing-tildes
> The resource at “https://www.reddit.com/r/all/best.json” was blocked because content blocking is enabled.
When I try to go to that URL in latest Firefox on MacOS.
Reddit new style also eats way more cpu cycles than needed, which is very important when you visit the site on potato hardware
https://addons.mozilla.org/en-US/firefox/addon/old-reddit-re...
The slowdown of the new design is really noticeable whenever I visit reddit on another browser or computer.
I refuse to believe anybody can honestly say they want to write JavaScript code unless it’s code that makes them write less javascript in future.
Just look at the history of JavaScript. It does not deserve the attention or human time that it currently gets (compared to other languages, assuming we could all decide simultaneously to replace JavaScript with another language).
So, let's not be too extreme here just because you don't like something. It gets really silly to hear HNers suggest the equivalent of "I don't understand how people own blue cars. They must secretly aspire to drive $myFavoriteColor. Don't they realize how stupid blue looks to me?"
It's time to switch to WASM though. Half native speed with almost no parsing overhead. As integration and tooling improve I see no reason to stick with JS.
It also rectifies a number of historical mistakes that are nearly impossible to fix. Mainly threading. WebWorkers etc are a huge hack. No atomic data structures, no shared memory, huge overhead. WASM will be many times faster than JS from threads alone. Add the natural speed advantage and you're looking at maybe a 20x performance difference.
But of course that's not the real cost. That's the computation cost. The real cost of websites switching to an application model directly targeting the DOM is the loss of accessible webpages and the chance that every time you're going to get owned. Weather it's some information leak from speculative execution or something else.
Running JS on every page these days is just as stupid as opening every attachment you get emailed to you.
Notable that they avoid the iPhone comparison. It runs circles around even the top end Androids for JS performance.
If my $70 android phone takes forever to execute something, I dont really care if my friend's iphone does it almost instantly.
As a result, they don’t have the tools they use to measure these stats on the iPhone either.
So if you are a web developer you get some good advice from this article related to JS not what phone to buy.
I imagine a lot of developers have recent iPhones. They are, depending on benchmark, up to 3x faster than a flagship Android. Which means the top to bottom chasm is much larger than the snippet suggests. Noting it would strengthen their point.
I agree that we the developers should not forget that a lot of people have less powerful hardware.
I sometimes hit thus problem at work, say we offer feature X like uploading an image and you can crop that image and apply a filter, how should I add this feature but not have the code even load in the browser if you don't intend to use, is there a pure JS way to do it? AFAIK thee is no good way to load a script at runtime and get an even when the file is loaded and parsed.
You can do this easily by creating a script element dynamically and then either:
1) Listen for the load event on that element, or
2) Have the dynamic script call a function that is already loaded.
Here is an example of the first technique:
let script = document.createElement( 'script' );
script.addEventListener( 'load', () => {
alert( 'three.js is loaded: ' + THREE );
});
script.src = 'https://ajax.googleapis.com/ajax/libs/threejs/r84/three.min.js';
document.head.appendChild( script );
https://jsfiddle.net/geary/szmc1L0h/9/Your example code works in all the browsers I tested so maybe it was an issue ith th particular script I was testing, there are third party scripts like for embedding an image editor, those could also use this trick to load some dependencies.
Great. so I was wrong then, this should work with most third party scripts.
2. Unless you have the Samsung SoC variant of just released Galaxy S10, pretty much all Android JS performance, including flagship, will be slower than the current entry iPhone, which is the iPhone 7.
And since the current Android flagship, along with middle range and lower end still has another 4 years of life in it, with roadmap that shows very slow improvement in the middle to low end Smartphones. May be we should just go back and ship HTML instead?