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