【问题标题】:Google Apps Script Webapp async loadingGoogle Apps 脚本 Webapp 异步加载
【发布时间】:2019-08-13 06:49:23
【问题描述】:

我正在使用 Google Apps 脚本编写一个网络应用程序。

为了减少加载时间,我让doGet(e) 使用一些 javascript 加载一个小文件,以异步加载其他 JS 和 CSS。

加载外部资源当然可以正常工作:

<head>
  <!-- loading external resources works fine of course -->
  <script src="https://cdnjs.cloudflare.c[...]/jquery.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.clou[...].1/jquery-ui.min.css">
</head>

但据我所知,这不能用我的应用程序脚本项目中的代码来完成,因为我无法提供指向该文件的直接链接。 所以我加了一点&lt;script&gt;

function loadScript(filePath) {
  google.script.run.withSuccessHandler(function(returnedValueFromGAS) {
    $('body').append(returnedValueFromGAS);
  }).loadScript(filePath);

  loadScript('someScriptFilepath');
  loadScript('someStyleFilepath')
}

以这种方式,我将&lt;script&gt;&lt;style&gt; 标记添加到我的HTML。 而且我不希望每个加载的文件都有一个回调,而是在我的所有(脚本)文件加载时都有一个回调。

到目前为止,这工作正常,但有一个主要缺点: Window-Load-Event 已经没有任何用处了。

如何像在其他环境中一样在&lt;head&gt; 中加载JS 和CSS 文件,以便load-event 仍然对我有用?

【问题讨论】:

  • of any use anymore. 为什么不呢?
  • 因为在我的小文档加载但不是我的 JS 加载的任何 JS 或 CSS 后触发事件。
  • 你能举一个具体的例子来说明你正在尝试做什么吗?为什么不将它包含在头部?如果没有,你是如何加载的?如果您正在加载脚本标签,load 事件仍会从该对象触发,您可以收听该事件。如果您通过google.script.run 加载,successHandler 将充当回调

标签: javascript google-apps-script web-applications


【解决方案1】:

而且我不希望每个加载的文件都有一个回调,而是在我的所有(脚本)文件加载时都有一个回调。

问题/解决方案:

  • 脚本正在一个接一个地调用服务器函数,而不是一个接一个(或一个接一个)。您应该嵌套回调('Callback hell')或使用 promises/async/await。

片段:

/**
 * Create a promise around old callback api
 * @param {String} func The server function to call
 * @param {Object} args The arguments to the server function 
 * @return Promise 
 */
const GSR = (func,...args) => 
  new Promise((resolve,reject)=>
    google.script.run
        .withSuccessHandler(resolve)
        .withFailureHandler(reject)[func](...args)
  );

const bodyAppend = function(returnedValueFromGAS) {
    $('body').append(returnedValueFromGAS);
}

//call GSR and append 
const GSRa = (func, ...args) => 
    GSR(func, ...args)
      .then(bodyAppend)
      .catch(e=>console.error(e.message));

function loadScriptClient() {//modified
  //Can also use async/await here
  Promise.all([GSRa('loadScript','someScriptFilepath'), GSRa('loadScript','someStyleFilepath')])
    .then(/*All Files loaded and appended at this point; Provide a final callback function here*/)
    .catch(e=>console.error(e.message));
}

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    相关资源
    最近更新 更多