能否仅下载含所需功能的定制版jQuery以提升站点加载性能?
解决方案
方案1:自定义裁剪jQuery构建
jQuery官方支持自定义构建,可以仅打包你需要的AJAX相关模块,剔除所有其他无用模块(比如DOM操作、动画、事件绑定、选择器等),最终构建出来的压缩版体积可控制在10KB以内,完全兼容旧浏览器,和原jQuery的$.get/$.post用法完全一致,无适配成本。
操作步骤:
- 安装Node.js环境,全局安装官方构建工具
grunt-cli - 拉取对应版本的jQuery源码,切换到所需版本分支(1.x分支兼容IE8及更早版本,3.x分支兼容现代浏览器)
- 执行自定义构建命令,仅保留AJAX及核心最小依赖模块:
grunt custom:-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-offset,-wrap,-sizzle - 构建完成后即可在dist目录获得自定义压缩版jQuery,直接引入项目使用即可
方案2:完全替代jQuery,手写兼容版$.get/$.post
如果连10KB的体积都想压缩,可以直接基于原生XMLHttpRequest封装两个和jQuery用法完全一致的函数,无需依赖任何库,最终代码体积不到1KB,兼容IE6及以上所有浏览器,原有业务代码不需要修改任何调用逻辑。
封装参考代码:
const $ = { get: function(url, data, success, dataType) { return this.ajax({ type: 'GET', url: url, data: data, success: success, dataType: dataType }) }, post: function(url, data, success, dataType) { return this.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType }) }, ajax: function(options) { const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP') const type = options.type || 'GET' let url = options.url const data = options.data || {} const dataType = options.dataType || 'json' const success = options.success || function() {} const error = options.error || function() {} // 参数序列化 let params = [] for (let key in data) { params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])) } params = params.join('&') if (type === 'GET' && params) { url += (url.indexOf('?') > -1 ? '&' : '?') + params } xhr.open(type, url, true) if (type === 'POST') { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { let res = xhr.responseText if (dataType === 'json') { try { res = JSON.parse(res) } catch (e) { error(xhr, 'parsererror', e) return } } success(res, xhr.statusText, xhr) } else { error(xhr, 'error', xhr.statusText) } } } xhr.send(type === 'POST' ? params : null) return xhr } }
内容的提问来源于stack exchange,提问作者I like eating pizza thursdays
相关产品推荐
相关产品推荐

