Google自定义搜索框不会在我的Gatsby项目中首次加载时显示,仅在重新加载或刷新时显示

问题描述 投票:1回答:1

目标:

加载网站时,它应该在导航栏中具有搜索框以及菜单项。

请参见下图:enter image description here

问题:

当前首次加载时,不会显示google自定义搜索框。但是,当您重新加载/刷新页面时,该页面将正常显示并正常运行。但这很烦人,因为人们可能不知道我有搜索框,直到他们刷新或重新加载页面。这就是第一次加载时的样子。

enter image description here

我已经尝试过:

根据google's instruction,我已完成以下操作:在我的gatsby项目的导航组件中,

import { Helmet } from "react-helmet"
...
 <Helmet>
    <script async src="https://cse.google.com/cse.js?cx=123:456"></script>
  </Helmet>
    <nav className="nav" >
      <div className="nav-container">
        <Link to="/">Home</Link>
        <Link to="/blog">All</Link>
        <Link to="/tags/food">Food</Link>
        <Link to="/tags/style">Style</Link>
        <Link to="/tags/living">Living</Link>
        <Link to="/tags/travel">Travel</Link>
        <Link to="/about">About</Link>  
        <div className="gcse-search"></div>
      </div> 
    </nav>

我确实使用过devtool,发现似乎没有任何内容加载到应该显示搜索框的div中。我不知道为什么会这样。

您可以在website live here上测试问题。

问题:

  1. 为什么会这样?

  2. 我如何调试和修复它?

gatsby google-custom-search
1个回答
0
投票
<script 

  async // <- This is the reason why your search box does not appear on first load

  src="https://cse.google.com/cse.js?cx=123:456"
></script>

您的页面呈现出来,而无需等待异步调用完成。在刷新时,异步调用已完成,因此可以呈现脚本。

© www.soinside.com 2019 - 2024. All rights reserved.