Tampermonkey 默认的 ES6 模板的工作流程是实时 Babel 转码,然后 eval 执行
存在的问题就是 Babel 的性能非常差,我的 5500 行自用脚本转码并执行需要 3400 ms,每一个页面都延迟这么长时间是不可忍受的
解决方法是用持久数据存储转码后的脚本,GM_getValue 和 GM_setValue 的用法教程里可以查到。添加存储后,每次修改代码并运行会完整转码一次,然后再次运行仅耗时 30ms,提速比较明显
一个简化的模板
// ==UserScript==
// @name ES6
// @match *://*/*
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
/* jshint ignore:start */
const text = (<><![CDATA[
/* jshint ignore:end */
/* jshint esnext: false */
/* jshint esversion: 6 */
// Your code here...
/* jshint ignore:start */
]]></>).toString();
/* jshint ignore:end */
if( text !== GM_getValue('esText') )
{
GM_setValue('esCode', Babel.transform( text , { presets: [ 'latest' ] } ).code );
GM_setValue('esText', text );
}
eval( GM_getValue('esCode') );