最近两年移动端的 Native 一直比较火,网上也有不少关于 Web 和 Native 的争论。看我标题,就知道其实我是来站队的。
Native 两个致命的缺陷
Web 的劣势
很多人都是认为 Web 慢,但是这个问题如何解决呢?
http://www.pocketjavascript.com/blog/2015/11/23/introducing-pokedex-org。
Ask any iOS or Android developer how we make our apps so fast, and most likely you'll hear about two major strategies:
- Eliminate network calls. Chatty network activity can kill the performance of a mobile app, even on a good 3G or 4G connection. Staring at a loading spinner is not a good user experience.
- Use background threads. To hit a silky-smooth 60 FPS, your operations on the main thread must take less than 16ms. Anything unrelated to the UI should be offloaded to a background thread.
其实 Web 已经有现成的方案了:
I believe the web is as capable of solving these problems as native apps, but most web developers just aren't aware that the tools are out there. For the network and concurrency problems, the web has two very good answers:
- Offline-first (e.g. IndexedDB and ServiceWorkers)
- Web workers
Offline-first 首先就需要一个 ClientDb。
For this app, I decided to use PouchDB for the Pokémon data (because it's good at sync), as well as LocalForage for app state data (because it has a nice key-value API). Both PouchDB and LocalForage are using IndexedDB inside a web worker, which means any database operations are fully non-blocking.
这里有一篇很有意思得文章:http://nolanlawson.com/2015/09/29/indexeddb-websql-localstorage-what-blocks-the-dom/。
However, it's also true that the Pokémon data isn't immediately available when the site is first loaded, because it takes awhile to sync from the server. So I'm also using a fallback strategy of "local first, then remote":
Background threads 就必须要用到 Web Worker 了。
简直完美,再也不用阻塞 UI 线程了。
地址:https://github.com/nolanlawson/pokedex.org,这才是未来。
顺便聊下其他的:
Meteor 虽然我不是很喜欢这种 JS 做全栈的方式,因为我一直认为 JS 的单线程方式非常不适合后端开发,但是这个框架的 DDP 协议还是很不错的一个东西,值得借鉴的地方很多。
WebWorker 其实这东西非常有用。https://gist.github.com/nolanlawson/d9e66349635452a95bb1
indexedDB 要想做离线应用,只能指望他了
ES7 Object.observe,虽然我更喜欢 clojurescript 的 immutable 的方式,但是看来不可能实现了。
WebAssembly 未来存在无数的可能