如何在加载页面时触发缓存文件?

pepwfjgg  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(354)

我有一个库存物品搜索工具,它可以过滤巨大的json文件(大约8mb),如果找到了物品,它只会以卡片格式显示有关该物品的所有信息。
因此,现在当我加载页面时,只有在我开始在页面的输入框中输入字符时,8mb的文件缓存才会开始。
如何改变这种行为,在加载页面时缓存文件,并将json对象传递给“get_item”函数,以便在我开始输入字符时就可以匹配项目。
我尝试使用domcontent.onload和其他各种onload触发器,但没有成功:(
请帮忙。
这是js代码:

const match_items = document.getElementById('match_items');

const get_item = async input_text => {
    const inventory_file = await fetch('/static/json/inventory_cookware_2020.json');
    const inventory_json = await inventory_file.json();

    let item_matches = inventory_json.filter(item => {
       const regex = new RegExp(`^${input_text}$`, 'gi');
       return item.match(regex);
    });

    if (input_text.length < 10){
        item_matches = [];
        match_item.innerHTML = '';

    }

    display_item_data(item_matches);
};

function display_item_data(item_matches){

code to display item data...
}
search.addEventListener('input', () => get_item(search.value)); ```

HTML--------------------------------------

   <div id="input_box">

        <input type="search" id="search" placeholder="Search Inventory">

   </div>

<div id="match_item"></div>
3xiyfsfu

3xiyfsfu1#

拥有 fetch 第一次访问页面时,在json文件的开头添加以下代码。这使用iife(立即调用的函数表达式)在页面首次加载时获取和填充数据。这个 search 在文件完成加载之前,将禁用输入。

let inventory_json;
const search = document.getElementById('search');
search.addEventListener('input', () => get_item(search.value));

(async () => {
  const inventory = await fetch('/static/json/inventory_cookware_2020.json');
  inventory_json = await inventory_file.json();
  search.disabled = false;
})();

const match_items = document.getElementById('match_items');

const get_item = input_text => {
  // This ensures the function won't run until the AJAX is complete
  // and inventory_json is populated
  if (!is_loaded) {
    return;
  }

  let item_matches = inventory_json.filter(item => {
    const regex = new RegExp(`^${input_text}$`, 'gi');
    return item.match(regex);
  });

  if (input_text.length < 10){
    item_matches = [];
    match_item.innerHTML = '';
  }

  display_item_data(item_matches);
};

HTML
<input type="text" id="search" placeholder="Search Inventory" disabled />

相关问题