每个页面 HEAD 几乎不变,通过监听 Link 和 Form 的点击,只处理Body内容替换,进而降低页面渲染最高的成本:JS和CSS的解析。
yarn remove turbolinks yarn add @hotwired/turbo
Turbo 的安装
import Turbo from "@hotwired/turbo"
然后将代码中所有的 Turbolinks 替换为 Turbo
$(document).on('turbo:load', function(){ // your code here // 等同于 ready 事件 })
Turbo 的平常使用
$(document).on('turbo:before-render', function(){ // your code here // 一些 unload 相关的代码 })
使用上的一些注意事项
幂等是导致放弃 Turbo 的根本原因
$(document).on('turbo:load', function(){ $(body).append("123"); })
解决幂等问题
$(document).on('turbo:load', function(){ $(body).append("123"); }) $(document).on('turbo:before-render', function(){ // undo this action })
<meta name="turbo-cache-control" content="no-cache">
方案一
方案二(推荐,关掉cache,体验更真实)
import { Controller } from "stimulus" import 'select2' export default class extends Controller { static targets = [ 'label' ] connect() { $(this.labelTarget).select2({ }) } disconnect() { $(this.labelTarget).select2('destroy') } }
方案三
临时关闭页面 turbo
<meta name="turbo-visit-control" content="reload">
<a href='' data-turbo='false'>
Turbo-Frame
示例https://github.com/windy/wblog_new/commit/83557a2d1da522ca6fa75281e089540e7e44bc3f
将前端复杂逻辑交还 Rails MVC 优雅处理
Turbo-Stream
用 Rails 控制前端 CRUD
示例交给下一个同学分享
其他补充
超级复杂的页面可以使用 ReactComponent 或 VueJS
By Li Yafei
Rails6 Turbo 详解
A senior Ruby on Rails developer