星期六, 12月 13, 2025

[GAS] 引用 css、javascript

學習前端開發時,習慣會把 html、css、javascript 檔案拆開來維護,但 Vibe Coding 產生的 Code 都是全部放在一起,該筆記是要記錄如何拆分檔案且能正常執行,基本上是透過 HtmlService.createTemplateFromFile() 來達成該需求

html、css、javascript 全部在一起
.gs Code

使用 HtmlService.createHtmlOutputFromFile 直接呼叫 index.html
function doGet() {
  return HtmlService.createHtmlOutputFromFile('index')
       .setTitle('Google Apps Script 引用 css、javascript 檔案');     
}
index.html
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <style>
    h2 {
      background-color: gray;
      text-align: left;
      padding: 10px;
    }
  </style>
</head>

<body>

  <h2>Google Apps Script 引用 css、javascript 檔案</h2>

  <button id="btnUpload" onclick="disableButton()">
    上傳檔案
  </button>

  <script>
    function disableButton() {
      const button = document.getElementById('btnUpload');

      if (button) { 
        button.innerText = "上傳處理中,請稍候... (From index.html)";

        button.disabled = true;

        button.style.backgroundColor = '#cccccc';
        button.style.color = '#666666';
        button.style.cursor = 'not-allowed';
      }      

    }
  </script>
</body>

</html>
執行結果

h2 以灰色背景呈現,按鈕按下去文字會變成 [上傳處理中,請稍候... (From index.html)]
拆分檔案

Google Apps Script 內只有 .html 和 .gs 兩種檔案格式,css 和 javascript 內容也是放在 html 檔案格式內,拆分後如下圖

.gs Code

因為 index.html 會呼叫 include() 函數來抓取 css.html 和 js.html 檔案,所以必須使用 HtmlService.createTemplateFromFile() 來呼叫 index.html
function doGet() {
  return HtmlService.createTemplateFromFile('index') // 回傳 HtmlTemplate
    .evaluate() // 把 HtmlTemplate 轉回 HtmlOuput
    .setTitle('Google Apps Script 引用 css、javascript 檔案');       
}

/**
 * index.html 內會透過呼叫 include() 來把 css.html 和 js.html 內容塞進 index.html 
 */
function include(fileName)
{
  return HtmlService.createHtmlOutputFromFile(fileName).getContent();
}
index.html

<?!= include("css") ?> 意思分兩個部分解釋
  • <? 函式 ?>:呼叫 .gs 檔案內的函式,即為 include()
  • !=:不進行 HTML 跳脫 (no escaping),會當成 html 語法的意思
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <!-- 載入 css -->
  <?!= include("css") ?>
</head>

<body>

  <h2>Google Apps Script 引用 css、javascript 檔案</h2>

  <button id="btnUpload" onclick="disableButton()">
    上傳檔案
  </button>

  <!-- 載入 Javascript -->
  <?!= include("js") ?>
</body>

</html>
css.html

css 語法必須用 style 標籤包起來
<style>
h2 {
  background-color: green;
  text-align: left;
  padding: 10px;
}
</style>
js.html

javascript 語法必須用 script 標籤包起來
<script>
function disableButton() {
  const button = document.getElementById('btnUpload');

  if (button) { 

    button.innerText = "上傳處理中,請稍候... (From js html)";
    
    button.disabled = true;
    
    button.style.backgroundColor = '#cccccc'; 
    button.style.color = '#666666';
    button.style.cursor = 'not-allowed';
  }      
}
</script>
執行結果

h2 以綠色背景呈現,按鈕按下去文字會變成 [上傳處理中,請稍候... (From js.html)]

沒有留言:

張貼留言