添加javascript
Static website generators like Gatsby and Jekyll are popular because they allow the creation of complex, templated pages that can be hosted anywhere. But the awesome simplicity of website generators is also limiting. Search is particularly hard. How do you allow users to search when you have no server functions and no database?
像Gatsby和Jekyll这样的静态网站生成器很受欢迎,因为它们允许创建可以在任何地方托管的复杂的模板化页面。 但是,网站生成器的简单性也很有限。 搜索特别困难。 当您没有服务器功能且没有数据库时,如何允许用户搜索?
With JavaScript!
使用JavaScript!
We've recently added Search to the TrackJS Documentation site, built using the Jekyll website generator and hosted on GitHub Pages. GitHub wasn't too keen on letting us run search functions on their servers, so we had to find another way to run full-text search on our documentation.
我们最近已将Search添加到TrackJS文档站点,该站点使用Jekyll网站生成器构建并托管在GitHub Pages上 。 GitHub不太热衷于让我们在其服务器上运行搜索功能,因此我们不得不寻找另一种方法来在文档中运行全文搜索。
Our documentation is about 43,000 words spread across 39 pages. That's actually not much data as it turns out--only 35 kilobytes when serialized for search. That's smaller than some JavaScript libraries.
我们的文档涵盖39页,共约43,000个单词。 事实证明,实际上并没有多少数据-序列化以进行搜索时只有35 KB。 比某些JavaScript库小。
We found a project called Lunr.js, which is a lightweight full-text search engine inspired by solr. Plus, it's only 8.4 kilobytes, so we can easily run it client-side.
我们找到了一个名为Lunr.js的项目,这是一个受solr启发的轻量级全文搜索引擎。 另外,它只有8.4 KB,因此我们可以轻松地在客户端运行它。
Lunr takes an array of keyed objects to build its index, so we need to get our data to the client in the right shape. We can serialize our data for search using Jekyll's native filters like: xml_escape, strip_html, and jsonify. We use these to build out an object with other important page context, like page title and url. This all comes together on a search.html page.
Lunr使用一组键控对象来构建其索引,因此我们需要以正确的形状将数据获取到客户端。 我们可以使用Jekyll的本地过滤器(例如 xml_escape , strip_html和jsonify对数据进行序列化以进行搜索。 我们使用它们来构建具有其他重要页面上下文的对象,例如页面标题和url。 所有这些都放在search.html页面上。
<ol id="search-results"></ol> <script> window.pages = { {% for page in site.pages %} "{{ page.url | slugify }}": { "title": "{{ page.title | xml_escape }}", "content": {{ page.content | markdownify | strip_newlines | strip_html | jsonify }}, "url": "{{ site.url | append: page.url | xml_escape }}", "path": "{{ page.url | xml_escape }}" }{% unless forloop.last %},{% endunless %} {% endfor %} }; </script> <script src="/lunr-2.3.5.min.js"></script> <script src="/search.js"></script>The above HTML fragment is the basic structure of the search page. It creates a JavaScript global variable, pages, and uses Jekyll data to build out the values from site content pages.
上面HTML片段是搜索页面的基本结构。 它创建一个JavaScript全局变量pages ,并使用Jekyll数据从站点内容页面中构建值。
Now we need to index our serialized page data with lunr. We'll handle our custom search logic in a separate search.js script.
现在我们需要用lunr索引序列化的页面数据。 我们将在单独的search.js脚本中处理自定义搜索逻辑。
var searchIndex = lunr(function() { this.ref("id"); this.field("title", { boost: 10 }); this.field("content"); for (var key in window.pages) { this.add({ "id": key, "title": pages[key].title, "content": pages[key].content }); } });We build out our new searchIndex by telling lunr about the shape of our data. We can even boost the importance of fields when searching, like increasing the importance of matches in page title over page content. Then, we loop over all our global pages and add them to the index.
通过告诉lunr数据的形状,我们构建了新的searchIndex 。 我们甚至可以在搜索时提高字段的重要性,例如提高页面标题中的匹配项比页面内容的重要性。 然后,我们遍历所有全局页面并将它们添加到索引中。
Now, we have all our documentation page data in a lunr search engine loaded on the client and ready for a search anytime the user visits the /search page.
现在,我们将所有文档页面数据都存储在客户端上的lunr搜索引擎中,并准备在用户访问/search页面时进行/search 。
We need to get the search query from the user to run a search. I want the user to be able to start a search from anywhere in the documentation--not just the search page. We don't need anything fancy for this, we can use an old-school HTML form with a GET action to the search page.
我们需要从用户那里获取搜索查询以运行搜索。 我希望用户能够从文档中的任何地方开始搜索,而不仅仅是搜索页面。 我们不需要任何花哨的东西,我们可以将老式HTML表单与对搜索页面的GET操作一起使用。
<form action="/search/" method="GET"> <input required type="search" name="q" /> <button type="submit">Search</button> </form>When the user enters their search query, it will bring them to the search page with their search in the q querystring. We can pick this up with some more JavaScript in our search.js and run the search against our index with it.
当用户输入搜索查询时,它将带他们进入q查询字符串中的搜索到搜索页面。 我们可以在search.js使用更多JavaScript来实现这一点,并使用它对索引进行搜索。
function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] === variable) { return decodeURIComponent(pair[1].replace(/\+/g, " ")); } } } var searchTerm = getQueryVariable("q"); // creation of searchIndex from earlier example var results = searchIndex.search(searchTerm); var resultPages = results.map(function (match) { return pages[match.ref]; });The results we get back from lunr don't have all the information we want, so we map the results back over our original pages object to get the full Jekyll page information. Now, we have an array of page results for the user's search that we can render onto the page.
我们从lunr获得的结果并没有我们想要的所有信息,因此我们将结果映射回原始页面对象以获取完整的Jekyll页面信息。 现在,我们有了用于用户搜索的页面结果数组,可以将其呈现到页面上。
Just like any other client-side rendering task, we need to inject our result values into an HTML snippet and place it into the DOM. We don't use any JavaScript rendering framework on the TrackJS documentation site, so we'll do this with plain-old JavaScript.
与其他客户端渲染任务一样,我们需要将结果值注入HTML代码段中并将其放入DOM中。 我们没有在TrackJS文档站点上使用任何JavaScript呈现框架,因此我们将使用普通JavaScript。
// resultPages from previous example resultsString = ""; resultPages.forEach(function (r) { resultsString += "<li>"; resultsString += "<a class='result' href='" + r.url + "?q=" + searchTerm + "'><h3>" + r.title + "</h3></a>"; resultsString += "<div class='snippet'>" + r.content.substring(0, 200) + "</div>"; resultsString += "</li>" }); document.querySelector("#search-results").innerHTML = resultsString;If you want to put other page properties into the results, like tags, you'd need to add them to your serializer so you have them in resultsPages.
如果要将其他页面属性(如标记)放入结果中,则需要将它们添加到序列化程序中,以便将它们包含在resultsPages 。
With some thought on design, and some CSS elbow-grease, it turns out pretty useful!
经过一些设计思考,再加上一些CSS肘部润滑脂,事实证明它非常有用!
I'm pretty happy with how it turned out. You can see it in action and checkout the final polished code on the TrackJS Documentation Page. Of course, with all that JavaScript, you'll need to watch it for bugs. TrackJS can help with that, grab your free trial of the best error monitoring service available today, and make sure your JavaScript keeps working great.
我对结果非常满意。 您可以在运行中看到它,并在TrackJS文档页面上查看最终的优美代码。 当然,使用所有这些JavaScript,您都需要注意它的错误。 TrackJS可以帮助您解决这一问题, 可以免费试用当今可用的最佳错误监视服务 ,并确保您JavaScript保持良好的运行状态。
Ready for even better search? Check out "Site Search with JavaScript Part 2", over on the TrackJS Blog. We expand on this example and improve the search result snippets to show better context of the search term, and dynamic highlighting of the search term in pages. It really improves the user experience.
准备好进行更好的搜索了吗? 在TrackJS Blog上查看“使用JavaScript进行站点搜索第2部分” 。 我们将扩展此示例,并改进搜索结果摘要以更好地显示搜索词的上下文,并在页面中动态突出显示搜索词。 它确实改善了用户体验。
翻译自: https://davidwalsh.name/adding-search-to-your-site-with-javascript
添加javascript
相关资源:jdk-8u281-windows-x64.exe