Google Apps Script Webapp 异步加载 [英] Google Apps Script Webapp async loading
问题描述
我正在使用 Google Apps 脚本编写一个网络应用程序.
I am writing a webapp using Google Apps Script.
为了减少加载时间,我让 doGet(e)
加载一个带有一些 javascript 的小文件,以异步加载其他 JS 和 CSS.
To reduce loading times I let doGet(e)
load a small file with some javascript to asynchronously load other JS and CSS.
加载外部资源当然很好:
Loading external resources works fine of course:
<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>
但据我所知,这无法使用我的应用程序脚本项目中的代码完成,因为我无法提供指向该文件的直接链接.这就是为什么我添加一点:
But from what I know this cannot be done with code inside my apps script project because I cannot provide a direct link to the file.
That's why I add a little <script>
:
function loadScript(filePath) {
google.script.run.withSuccessHandler(function(returnedValueFromGAS) {
$('body').append(returnedValueFromGAS);
}).loadScript(filePath);
loadScript('someScriptFilepath');
loadScript('someStyleFilepath')
}
通过这种方式,我将 和
标签添加到我的 HTML 中.而且我不希望每个加载的文件都有一个回调,而是在加载我的所有(脚本)文件时有一个回调.
In this manner I add <script>
and <style>
tags to my HTML.
And I would like to have not one callback for every loaded file, but one callback when all my (script-)files are loaded.
到目前为止,这工作正常,但有一个主要缺点:Window-Load-Event 不是任何不用了.
This works fine so far with one major drawback: The Window-Load-Event is not of any use anymore.
如何像在其他环境中那样在 中加载 JS 和 CSS 文件,以便
load-event
仍然对我有用?
How can I load JS and CSS files in the <head>
like I would do in other environments so that the load-event
still is of use for me?
推荐答案
而且我不希望每个加载的文件都有一个回调,而是当我的所有(脚本)文件加载时一个回调.
And I would like to have not one callback for every loaded file, but one callback when all my (script-)files are loaded.
问题/解决方案:
- 脚本正在一个接一个地调用服务器功能,而不是一个接一个地(或一个一个地).您应该嵌套回调('回调地狱')或使用 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));
}
参考:
- 承诺
- Promises#All
这篇关于Google Apps Script Webapp 异步加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!