Merge pull request #2633 from GuillaumeGomez/speed-up-loading

Speed up search index loading
This commit is contained in:
Eric Huss 2025-04-21 00:10:57 +00:00 committed by GitHub
commit 14aeb0cb83
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 15 additions and 7 deletions

View file

@ -3,7 +3,7 @@
/* global Mark, elasticlunr, path_to_root */ /* global Mark, elasticlunr, path_to_root */
window.search = window.search || {}; window.search = window.search || {};
(function search(search) { (function search() {
// Search functionality // Search functionality
// //
// You can use !hasFocus() to prevent keyhandling in your key // You can use !hasFocus() to prevent keyhandling in your key
@ -289,6 +289,9 @@ window.search = window.search || {};
// If reloaded, do the search or mark again, depending on the current url parameters // If reloaded, do the search or mark again, depending on the current url parameters
doSearchOrMarkFromUrl(); doSearchOrMarkFromUrl();
// Exported functions
config.hasFocus = hasFocus;
} }
function unfocusSearchbar() { function unfocusSearchbar() {
@ -522,6 +525,4 @@ window.search = window.search || {};
loadScript(path_to_root + '{{ resource "searchindex.js" }}', 'search-index'); loadScript(path_to_root + '{{ resource "searchindex.js" }}', 'search-index');
// Exported functions
search.hasFocus = hasFocus;
})(window.search); })(window.search);

View file

@ -66,7 +66,13 @@ pub fn create_files(
if search_config.copy_js { if search_config.copy_js {
static_files.add_builtin( static_files.add_builtin(
"searchindex.js", "searchindex.js",
format!("Object.assign(window.search, {});", index).as_bytes(), // To reduce the size of the generated JSON by preventing all `"` characters to be
// escaped, we instead surround the string with much less common `'` character.
format!(
"window.search = JSON.parse('{}');",
index.replace("\\", "\\\\").replace("'", "\\'")
)
.as_bytes(),
); );
static_files.add_builtin("searcher.js", searcher::JS); static_files.add_builtin("searcher.js", searcher::JS);
static_files.add_builtin("mark.min.js", searcher::MARK_JS); static_files.add_builtin("mark.min.js", searcher::MARK_JS);

View file

@ -773,9 +773,10 @@ mod search {
fn read_book_index(root: &Path) -> serde_json::Value { fn read_book_index(root: &Path) -> serde_json::Value {
let index = root.join("book/searchindex.js"); let index = root.join("book/searchindex.js");
let index = fs::read_to_string(index).unwrap(); let index = fs::read_to_string(index).unwrap();
let index = index.trim_start_matches("Object.assign(window.search, "); let index = index.trim_start_matches("window.search = JSON.parse('");
let index = index.trim_end_matches(");"); let index = index.trim_end_matches("');");
serde_json::from_str(index).unwrap() // We need unescape the string as it's supposed to be an escaped JS string.
serde_json::from_str(&index.replace("\\'", "'").replace("\\\\", "\\")).unwrap()
} }
#[test] #[test]