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

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode Profile a React App for Performance
Speed up your App with Web Workers
2019-10-04 · via Kent C. Dodds Blog

Watch "Get started with Web Workers" on egghead.io

I remember when I started learning about threads in Java. My college professor pulled up iTunes, hit play on a song and said: "if it weren't for threads, I wouldn't be able to click any of these buttons at the same time iTunes is playing this music."

JavaScript is single-threaded. This means that any JavaScript environment will not run multiple lines of JavaScript in the same process simultaneously (the browser handles audio-playback separate from the thread it gives you for your JavaScript which is why your code can run while music is playing in the browser). The single threaded-ness of JavaScript drastically simplifies a lot of programming in JavaScript, but it does come with some drawbacks.

One of the most significant of these drawbacks comes in the form of user experience. To illustrate my point, go ahead and open a new tab to twitter.com and open your browser DevTools console. Then copy/paste this and hit enter:

while (true) {}

Can you interact with the web page anymore? No? That's because your code is keeping the JavaScript thread so busy just hanging out in that infinite while loop that no other JavaScript can do anything. (If you're stuck and you can't close that tab, my apologies. In Chrome you can stop the tab by going to "More tools" -> "Task Manager" and selecting the tab and clicking "End Process").

So the moral of the story is don't use infinite loops in your code right? Well, I think we all can agree on that, but I've got a stronger, more practical point to this. What if you have some code that takes a long time to run? Maybe it's... I don't know... Mining bitcoin or something. With some kinds of computations, there's only so much performance optimization you can do before you just hit the limits of the machine that's running your code. So are your users just stuck with a really bad experience using your website whenever that code has to run? No!

Enter Web Workers

You know how you can have multiple tabs open in your browser? Each one of those tabs is running the JavaScript for that page in its own thread. So just because JavaScript is single-threaded, doesn't mean the browser can't spin up multiple threads to run different JavaScript files.

Web Workers are a browser standard that enables you to do just that! And you can even communicate between those different threads (with some limitations, which we won't get into in this post).

Super Simple Start to Web Workers

Here you go:

<script src="main.js"></script>
// main.js
const worker = new Worker('worker.js')
worker.postMessage('Hello Worker')
worker.onmessage = (e) => {
	console.log('main.js: Message received from worker:', e.data)
}
// if you want to "uninstall" the web worker then use:
// worker.terminate()
// worker.js
this.onmessage = (e) => {
	console.log('worker.js: Message received from main script', e.data)
	this.postMessage('Hello main')
}

You can preview this here (open your console): super-simple-web-worker.netlify.com

There you go. You can now run your bitcoin miner without locking up the main thread! In fact, in the Chrome DevTools Sources tab, it shows that we have another thread:

Chrome DevTools Sources tab showing a thread titled worker.js

You can even put a breakpoint in your code and debug it like you're used to. Neat!

Practical use

I remember when Web Workers became a thing. And I guess it was longer ago than I remember because IE10 supports Web Workers. So if you have to support a browser that's not supporting Web Workers then I'm sorry, I just don't know what to tell you.

For the rest of us, how do we go from this simple one-file setup to something that will scale well/support/modules/etc? Well, my favorite solution to this is workerize by Jason Miller:

Workerize logo

It's awesome, but even more awesome is the sibling project by Jason called workerize-loader which is a webpack loader for workerize which basically means you can put any module (and the modules that it imports) into a webworker.

It's really easy to use too. I teach about this in my React Performance workshop. There are a few exercises that show you how to optimize a client-side search input component which allows you to do a filter of thousands of cities using match-sorter and Downshift.

We have a module that has the whole list of cities and exposes a getItems function which accepts the user's input and then returns an array of the matching cities.

That workshop material uses react-scripts (create-react-app). Here's some of the code from my material:

// eslint-disable-next-line import/no-webpack-loader-syntax
import makeFilterCitiesWorker from 'workerize!./filter-cities'

const { getItems } = makeFilterCitiesWorker()

export { getItems }

The workerize! thing in the import statement is a fancy webpack syntax to tell webpack to treat that module specially (specifically to pipe it through the workerize-loader so Jason can do his magic on it to get it into a web worker).

Putting the getItems code into a web worker did wonders to speed up my demo. One catch to this is that before getItems was synchronous, but communication between the main thread and a worker thread is asynchronous, so I had to alter my app code a little bit to handle the asynchrony, but it was totally worthwhile and improved the user experience a lot.

Conclusion

I hope this helps you out! I have a feeling that we don't use web workers as much as we probably could/should, so profile your app and see whether there are any hot-spots in your JavaScript code that could benefit from a separate thread. Good luck!