【问题标题】:GSCRIPT - How to cache HTML page content?GSCRIPT - 如何缓存 HTML 页面内容?
【发布时间】:2017-01-23 17:01:43
【问题描述】:

我有点卡在这里。

我有一个要加载的 HTML 模板,在这个页面中有很多 JavaScript 代码。

我正在尝试通过使用我的 Google 表格的 onOpen() 缓存模板来加速操作。我不知道如何缓存我的 HTML 页面 CalForm.html(来自我的内部 Google Sheet 脚本)。

这是我现在拥有的:

创建缓存

function CacheCreate() {

CacheService.getScriptCache().put('CalCache', 'CalForm');
 Browser.msgBox("done");
}

获取缓存

var evalSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Evaluation');
  var row = evalSheet.getActiveCell().getRow();

  var CalCache2 = CacheService.getScriptCache().get('CalCache');

  Browser.msgBox(CacheService.getScriptCache().get('CalCache'))

  initialize(row);

  //var cache = CacheService.getScriptCache();
  //var cache2 = cache.get('rss-feed-contents');

  //Browser.msgBox(cache.get('rss-feed-contents'));

var html = HtmlService
      .createTemplateFromFile(CalCache2)
      .evaluate()
      .setWidth(1200)
      .setHeight(560)
      .setSandboxMode(HtmlService.SandboxMode.NATIVE);
  SpreadsheetApp.getUi().showModalDialog(html, 'Calculatrice');

感谢您的帮助!

【问题讨论】:

    标签: caching google-apps-script google-apps


    【解决方案1】:

    首先,您需要从“内部 Google 表格脚本”中获取 HTML,假设您的脚本中有一个名为“template.html”的文件,以下代码将获取 HTML(字符串格式)。

    var template = HtmlService.createHtmlOutputFromFile('template').getContent();
    

    我运行检查以查看数据是否已经在缓存中...

    function getObjectsFromCache(key, objects, flush) 
    {
      Logger.log("Running:  getObjectsFromCache(" + key + ", objects)");
      var cache = CacheService.getScriptCache();
      var cached = cache.get(key);
      flush = false;  // 1st run 45.33, 2nd run 46.475
      //flush = true;// 65.818 seconds
      if (cached != null && flush != true) 
      {
        Logger.log("\tEXISTING DATA -> ");
        cached = cache.get(key);
      }
      else
      {
        Logger.log("\tNEW DATA -> ");
        //Logger.log("\tJSON.stringify(objects):  " + JSON.stringify(objects) + ", length:  " + objects.length);
        //If you're working with spreadsheet objects, or array data, you'll want to put the data in the cache as a string, and then reformat the data to it's original format, when it is returned.
        //cache.put(key, JSON.stringify(objects), 1500); // cache for 25 minutes
        //In your case, the HTML does not need to be stringified.
        cache.put(key, objects, 1500); // cache for 25 minutes
        cached = objects;
      }
      return cached;
    }
    

    我注释掉了 JSON.Stringify(objects),因为在我的原始代码中,我使用另一个名为 formatCachedData(cache, key) 的函数来返回不同类型的数据 - 多维数组(电子表格数据),或者来自 AdminDirectory.Users.list({...}) 的 Google 用户数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2021-06-04
      相关资源
      最近更新 更多