我写了一个

2015. 6. 12.

@CSS魔法

history.state 

Polyfill 项目

  • 为什么?

  • 怎样……实现?

  • 怎样……测试?

(30 ~ 45 分钟)

为什么?

Traditional History API

  • history.length 属性
  • history.go() 方法
  • history.back() 方法
  • history.forward() 方法 

HTML5 History API

  • history.pushState(state, title, url) 方法
  • history.relaceState(state, title, url) 方法
  • window 的 "popstate" 事件

如何获取当前 state?

  • "popstate" 事件的 event.state 属性
    
    
    
  • history.state 属性

任何时候都可获取

必须提前监听此事件

但是……

  • iOS 5-
  • Android 4.3-
  • ……

以下环境没有实现 history.state 属性:

We need a polyfill !

怎样……实现?

(讨论)

如何写好一个 Polyfill 脚本?

  • 在不需要打补丁的环境中,直接退出

  • 在需要打补丁的环境中,模拟原生行为

  • 在无法打补丁的环境中,向控制台报错后退出

实现中的要点

  • history.pushState() 被调用时
  • history.relaceState() 被调用时
  • 前进/后退时

“当 state 变化时手动更新 history.state 属性。”

"popstate" 事件触发时)

怎样……测试?

(讨论)

测试框架

  • Mocha 测试框架

  • Chai 断言库

  • BDD 风格

测试中的要点

“测试页面不能刷新!”

  • 如何刷新沙盒?

  • 如何得知沙盒已加载完成?

  • 沙盒与宿主环境(测试页面)如何通信?

“如何重复调用并测试同一 API?”

Sandbox!

我写的 history.state 的 Polyfill 项目

$ npm install history.state

      Star

You'll need it, I bet.

// polyfill
historyState.polyfill()

// detection
historyState.isSupported()

API

Q & A

Thank you!

我写了一个 history.state 的 Polyfill 项目

By CSS魔法

我写了一个 history.state 的 Polyfill 项目

Repo: cssmagic/history.state

  • 1,681