I have a search function on a page that displays a couple of thousand entries.
(我在一个显示数千个条目的页面上具有搜索功能。)
it is a simple html searchbox:
(这是一个简单的html搜索框:)
<form class="text-center" onkeydown="return event.key != 'Enter';">
<input id="coursesearchbox" autocomplete="off" type="search" oninput="filterCourses()">
</form>
which is tied to a javascript function that hides all list items, and then shows all list items that match the search term in their data attribute.
(它与javascript函数绑定在一起,该javascript函数隐藏所有列表项,然后在其data属性中显示与搜索词匹配的所有列表项。)
I'm also using a sleep function to only run the search when no new input is made for at least 250ms:(我还使用sleep函数仅在至少250ms内未进行任何新输入时才运行搜索:)
//filters courses in the course search tab
async function filterCourses() {
if (coursesearchbox.value.length > 2) {
hideAllCourses();
var searchterm = coursesearchbox.value;
await sleep(250);
if (searchterm == coursesearchbox.value) {
var searchedCourses = document.querySelectorAll("[data-index*=" + searchterm + "]");
for (var i = 0; i < searchedCourses.length; i++) {
searchedCourses[i].style.display = "list-item";
}
}
} else {
showAllCourses();
}
}
//hides all courses
function hideAllCourses() {
for (var i = 0; i < sortableListItems.length; i++) {
sortableListItems[i].style.display = "none";
}
}
//shows all courses
function showAllCourses() {
for (var i = 0; i < sortableListItems.length; i++) {
sortableListItems[i].style.display = "list-item";
}
}
My problem is the performance of the script.
(我的问题是脚本的性能。)
What's funny for me, is that the slowest part is not actually searching for stuff, but deleting your search term, thus running showAllCourses().(对我来说有趣的是,最慢的部分不是实际搜索内容,而是删除搜索词,从而运行showAllCourses()。)
Apparently the browser takes a long time switching back all the list items to display: list-item.(显然,浏览器需要很长时间才能切换回所有要显示的列表项:list-item。)
I tried using visibility: collapse instead of display:none, and that made it a lot faster, but unfortunately it does not work in Chrome.
(我尝试使用了能见度:不显示而不显示:没有,这使它运行起来快得多,但不幸的是,它在Chrome中不起作用。)
Is there any other way I can speed this up?
(我还有其他方法可以加快速度吗?)
I think it might be slow because the browser re-renders the page everytime a list-item is switched back to display: list-item, so maybe if I could stop the page from re-rendering until the for-loop in showAllCourses() is done, that would help?(我认为这可能会很慢,因为每次将列表项切换回显示时浏览器都会重新渲染页面:list-item,所以也许我可以停止页面的重新渲染,直到showAllCourses()中的for循环为止完成了,那会有所帮助吗?)
ask by Vintermute translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…