HTML Service:最佳做法
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
使用 HTML 服務建立使用者介面時,許多模式和做法都與其他類型的網頁開發相同。不過,有些方面是 Apps Script 環境獨有的,或是值得特別強調。下文將介紹一些最佳做法,方便您在開發自己的 HTML 服務 UI 時參考。
HTML、CSS 和 JavaScript 分開
將所有 HTML、CSS 和 JavaScript 程式碼放在一個檔案中,可能會導致專案難以閱讀和開發。雖然 Apps Script 規定用戶端程式碼必須放在 .html 檔案中,但您仍可將 CSS 和用戶端 JavaScript 分別放在不同檔案中,然後使用自訂函式將這些檔案納入主要 HTML 網頁。
以下範例會在 Code.gs 檔案中定義自訂伺服器端 include()
函式,將 Stylesheet.html 和 JavaScript.html 檔案內容匯入 Page.html 檔案。使用列印指令碼片段呼叫時,這個函式會將指定檔案內容匯入目前檔案。請注意,內含檔案含有 <style>
和 <script>
標記,因為這些是 HTML 程式碼片段,而非純 .css 或 .js 檔案。
Code.gs
function doGet(request) {
return HtmlService.createTemplateFromFile('Page')
.evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('Stylesheet'); ?>
</head>
<body>
<h1>Welcome</h1>
<p>Please enjoy this helpful script.</p>
<?!= include('JavaScript'); ?>
</body>
</html>
Stylesheet.html
<style>
p {
color: green;
}
</style>
JavaScript.html
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
非同步載入資料,而非在範本中載入
範本化 HTML 可用於快速建構簡單的介面,但應限制使用,確保 UI 具有回應性。範本中的程式碼會在網頁載入時執行一次,且在處理完成前,不會將任何內容傳送至用戶端。如果腳本程式碼中有長時間執行的工作,可能會導致 UI 顯示緩慢。
使用 scriptlet 標記執行快速的一次性工作,例如納入其他內容或設定靜態值。所有其他資料都應使用 google.script.run
呼叫載入。以這種非同步方式編碼較為困難,但可加快 UI 載入速度,並讓 UI 有機會向使用者顯示微調器或其他載入訊息。
不要 - 載入範本
<p>List of things:</p>
<? var things = getLotsOfThings(); ?>
<ul>
<? for (var i = 0; i < things.length; i++) { ?>
<li><?= things[i] ?></li>
<? } ?>
</ul>
正確做法:非同步載入
<p>List of things:</p>
<ul id="things">
<li>Loading...</li>
</ul>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(showThings)
.getLotsOfThings();
});
function showThings(things) {
var list = $('#things');
list.empty();
for (var i = 0; i < things.length; i++) {
list.append('<li>' + things[i] + '</li>');
}
}
</script>
使用 HTTPS 載入資源
如果網頁是使用較新的 IFRAME
沙箱模式提供,包括未使用 HTTPS 提供的 JavaScript 或 CSS 檔案,就會導致錯誤,如下所示。
複合型內容:網頁「https://...」是透過 HTTPS 載入,但要求了不安全的指令碼「http://...」。這項要求已遭封鎖;
內容必須透過 HTTPS 提供。
大多數熱門程式庫都支援 HTTP 和 HTTPS,因此通常只要在網址中插入額外的「s」即可切換。
使用 HTML5 文件類型宣告
如果網頁是使用較新的 IFRAME
沙箱模式放送,請務必在 HTML 檔案頂端加入下列程式碼片段。
<!DOCTYPE html>
這個文件類型宣告會告訴瀏覽器,您設計的網頁適用於新式瀏覽器,因此不應使用「相容模式」轉譯網頁。即使您不打算使用新式 HTML5 元素或 JavaScript API,這項做法也有助於確保網頁正確顯示。
最後載入 JavaScript
許多網頁開發人員建議在網頁底部載入 JavaScript 程式碼,以提高回應速度,這對 HTML 服務而言更是重要。將 <script>
標記移至網頁結尾,即可在處理 JavaScript 前轉譯 HTML 內容,向使用者顯示微調器或其他訊息。
善用 jQuery
jQuery 是熱門的 JavaScript 程式庫,可簡化網頁開發中的許多常見工作。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間:2025-08-31 (世界標準時間)。"],[[["\u003cp\u003eSeparate your HTML, CSS, and JavaScript into different files for better organization and readability, using a custom server-side function to include them in the main HTML.\u003c/p\u003e\n"],["\u003cp\u003eLoad data asynchronously using \u003ccode\u003egoogle.script.run\u003c/code\u003e to keep the UI responsive and avoid delays caused by long-running tasks in templates.\u003c/p\u003e\n"],["\u003cp\u003eEnsure all resources are loaded over HTTPS to prevent mixed content errors, especially in sandbox mode.\u003c/p\u003e\n"],["\u003cp\u003eUtilize the HTML5 document type declaration (\u003ccode\u003e<!DOCTYPE html>\u003c/code\u003e) to ensure your page is rendered correctly in modern browsers.\u003c/p\u003e\n"],["\u003cp\u003eLoad JavaScript code at the end of your page to prioritize HTML content rendering and improve perceived performance.\u003c/p\u003e\n"]]],[],null,["# HTML Service: Best Practices\n\nCreating user interfaces with the HTML service follows many of the same patterns\nand practices as other types of web development. However, there are some aspects\nthat are unique to the Apps Script environment or are otherwise worth\nhighlighting. Below we'll cover some best practices you should keep in mind when\ndeveloping your own HTML-service UIs.\n\nSeparate HTML, CSS, and JavaScript\n----------------------------------\n\nKeeping all the HTML, CSS, and JavaScript code in one file can make your project\ndifficult to read and develop. While Apps Script does require client-side code\nto be placed in .html files, you can still separate your CSS and client-side\nJavaScript into different files and then include them in the main HTML page\nwith a custom function.\n\nThe example below defines a custom server-side `include()` function in the\nCode.gs file to import the Stylesheet.html and JavaScript.html file content\ninto the Page.html file. When called using\n[printing scriptlets](/apps-script/guides/html/templates#printing_scriptlets),\nthis function imports the specified file content into the current file. Notice\nthat the included files contain `\u003cstyle\u003e` and `\u003cscript\u003e` tags because\nthey're HTML snippets and not pure .css or .js files. \n\n### Code.gs\n\n```html\nfunction doGet(request) {\n return HtmlService.createTemplateFromFile('Page')\n .evaluate();\n}\n\nfunction include(filename) {\n return HtmlService.createHtmlOutputFromFile(filename)\n .getContent();\n}\n```\n\n### Page.html\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n \u003chead\u003e\n \u003cbase target=\"_top\"\u003e\n \u003c?!= include('Stylesheet'); ?\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003ch1\u003eWelcome\u003c/h1\u003e\n \u003cp\u003ePlease enjoy this helpful script.\u003c/p\u003e\n \u003c?!= include('JavaScript'); ?\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n```\n\n### Stylesheet.html\n\n```html\n\u003cstyle\u003e\np {\n color: green;\n}\n\u003c/style\u003e\n```\n\n### JavaScript.html\n\n```html\n\u003cscript\u003e\nwindow.addEventListener('load', function() {\n console.log('Page is loaded');\n});\n\u003c/script\u003e\n```\n\nLoad data asynchronously, not in templates\n------------------------------------------\n\n[Templated HTML](/apps-script/guides/html/templates) can be used to quickly\nbuild simple interfaces, but its use should be limited to ensure your UI is\nresponsive. The code in templates is executed once when the page is loaded, and\nno content is sent to the client until the processing is complete. Having\nlong-running tasks in your scriptlet code can cause your UI to appear slow.\n\nUse scriptlet tags for quick, one-time tasks such as including other content\nor setting static values. All other data should be loaded using\n[`google.script.run`](/apps-script/guides/html/communication) calls.\nCoding in this asynchronous manner is more difficult but allows the UI to load\nmore quickly and gives it the opportunity to present a spinner or other\nloading message to the user.\n\nDon't --- load in templates \n\n```html\n\u003cp\u003eList of things:\u003c/p\u003e\n\u003c? var things = getLotsOfThings(); ?\u003e\n\u003cul\u003e\n \u003c? for (var i = 0; i \u003c things.length; i++) { ?\u003e\n \u003cli\u003e\u003c?= things[i] ?\u003e\u003c/li\u003e\n \u003c? } ?\u003e\n\u003c/ul\u003e\n```\n\nDo --- load asynchronously \n\n```html\n\u003cp\u003eList of things:\u003c/p\u003e\n\u003cul id=\"things\"\u003e\n \u003cli\u003eLoading...\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cscript\nsrc=\"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"\u003e\n\u003c/script\u003e\n\u003cscript\u003e\n// The code in this function runs when the page is loaded.\n$(function() {\n google.script.run.withSuccessHandler(showThings)\n .getLotsOfThings();\n});\n\nfunction showThings(things) {\n var list = $('#things');\n list.empty();\n for (var i = 0; i \u003c things.length; i++) {\n list.append('\u003cli\u003e' + things[i] + '\u003c/li\u003e');\n }\n}\n\u003c/script\u003e\n```\n\nLoad resources using HTTPS\n--------------------------\n\nIf your page is served using the newer `IFRAME`\n[sandbox mode](/apps-script/guides/html/restrictions#sandbox_mode), including\nJavaScript or CSS files not served using HTTPS will result in errors like the\none below.\n\u003e Mixed Content: The page at 'https://...' was loaded over HTTPS, but\n\u003e requested an insecure script 'http://...'. This request has been blocked;\n\u003e the content must be served over HTTPS.\n\nMost popular libraries support both HTTP and HTTPS, so switching is usually\njust a matter of inserting an addition 's' into the URL.\n\nUse the HTML5 document type declaration\n---------------------------------------\n\nIf your page is served using the newer `IFRAME`\n[sandbox mode](/apps-script/guides/html/restrictions#sandbox_mode), make sure\nto include the following snippet of code at the top of your HTML file. \n\n \u003c!DOCTYPE html\u003e\n\nThis document type declations tells the browser that you designed the page for\nmodern browsers, and that it shouldn't render your page using\n[quirks mode](http://en.wikipedia.org/wiki/Quirks_mode). Even if you don't plan\nto take advantage of modern HTML5 elements or JavaScript APIs, this will help\nensure your page is displayed correctly.\n\nLoad JavaScript last\n--------------------\n\nMany web developers recommend loading JavaScript code at the bottom of the page\nto increase responsiveness, and this is even more important with the HTML\nservice. Moving your `\u003cscript\u003e` tags to the end of your page will let HTML\ncontent render before the JavaScript is processed, allowing you to present a\nspinner or other message to the user.\n\nTake advantage of jQuery\n------------------------\n\n[jQuery](http://jquery.com/) is a popular JavaScript library that simplifies\nmany common tasks in web development."]]