本地搜索使用json替换xml,速度更快

## xml文件格式本地测试
![](https://cdn.jsdelivr.net/gh/Rr210/image@master/hexo/api/20211006095512.png)
## json文件本地测试
![](https://cdn.jsdelivr.net/gh/Rr210/image@master/hexo/api/20211006095847.png)
## json文件线上测试
![](https://cdn.jsdelivr.net/gh/Rr210/image@master/hexo/api/20211006100635.png)
## 模式切换
两种模式 切换 只需要修改全局配置文件的搜索插件文件格式(json/xml)
This commit is contained in:
Harry
2021-10-06 14:52:52 +08:00
committed by GitHub
parent 7e729cff79
commit 312a766901

View File

@@ -41,20 +41,24 @@ window.addEventListener('load', () => {
searchClickFn()
})
function search (path) {
fetch(GLOBAL_CONFIG.root + path)
.then(response => response.text())
.then(str => new window.DOMParser().parseFromString(str, 'text/xml'))
.then(data => {
const datas = [...data.querySelectorAll('entry')].map(function (item) {
const content = item.querySelector('content')
async function search(path) {
let datas = []
const typeF = path.split('.')[1]
const response = await fetch(GLOBAL_CONFIG.root + path)
if (typeF === 'json') {
datas = await response.json()
} else if (typeF === 'xml') {
let res = await response.text()
let t = await new window.DOMParser().parseFromString(res, 'text/xml')
let a = await t
datas = [...a.querySelectorAll('entry')].map(function (item) {
return {
title: item.querySelector('title').textContent,
content: content ? content.textContent : '',
content: item.querySelector('content').textContent,
url: item.querySelector('url').textContent
}
})
}
const $input = document.querySelector('#local-search-input input')
const $resultContent = document.getElementById('local-search-results')
$input.addEventListener('input', function () {
@@ -100,6 +104,8 @@ window.addEventListener('load', () => {
const content = data.content.trim().replace(/<[^>]+>/g, '')
if (firstOccur >= 0) {
// cut out 130 characters
// let start = firstOccur - 30 < 0 ? 0 : firstOccur - 30
// let end = firstOccur + 50 > content.length ? content.length : firstOccur + 50
let start = firstOccur - 30
let end = firstOccur + 100
@@ -142,6 +148,5 @@ window.addEventListener('load', () => {
$resultContent.innerHTML = str
window.pjax && window.pjax.refresh($resultContent)
})
})
}
})