Select2 数据量大导致加载卡顿解决方案
一、Select2 初始化
1. HTML
<select id="select2_test">
<option value="请选择" selected="selected">请选择</option>
</select>
2. JS
模拟十万条选项添加到 Select2 控件。
var data = new Array();
for (var i = 0; i < 100000; i++) {
data.push( { id: i, text: "第 {0} 项".replace("{0}", i) } );
}
$("#select2_test").select2({
data: data,
placeholder: "请选择",
width: '300px'
});
3. 渲染效果
二、Select2 卡顿解决方案
数据量特别大(Select2 选择项过多)时,会导致点击 Select 框非常卡。
但是数据量特别大时,User 通过下拉框一个个去查找选项来选择也不太可能,所以通过仅显示部分选项来避免卡顿,其他选项 User 可通过搜索框搜索选择来解决此问题。
1. 修改 Select2 的 JS 源码
// Select2 部分源码
SelectAdapter.prototype.query = function (params, callback) {
var data = [];
var self = this;
var $options = this.$element.children();
$options.each(function () {
if (
this.tagName.toLowerCase() !== 'option' &&
this.tagName.toLowerCase() !== 'optgroup'
) {
return;
}
var $option = $(this);
var option = self.item($option);
var matches = self.matches(params, option);
if (matches !== null) {
data.push(matches);
}
});
callback({
results: data
});
};
// 修改后的代码
SelectAdapter.prototype.query = function (params, callback) {
var data = [];
var self = this;
var $options = this.$element.children();
$options.each(function () {
// 让 Select2 只加载 200 个选项
if (data.length > 200) {
return;
}
if (
this.tagName.toLowerCase() !== 'option' &&
this.tagName.toLowerCase() !== 'optgroup'
) {
return;
}
var $option = $(this);
var option = self.item($option);
var matches = self.matches(params, option);
if (matches !== null) {
data.push(matches);
}
});
callback({
results: data
});
};
2. 修改后的渲染效果
只加载了 200 条选项(从 0 开始)
其他未加载选项可通过搜索找到
License:
CC BY 4.0