HTML 文件中包含的脚本不在 Google Apps 脚本 HTML 服务中 运行

Included script in HTML file does not run in Google Apps Script HTMLService

我有一个正在加载的模板 HTML 文件,可以使用下面代码中所示的函数加载其他 HTML。我正在尝试在脚本标签中获取 运行 包含的函数。这是 HTML Google Sheet 脚本中的服务。

Code.gs我有

function doGet() {
  var template = HtmlService.createTemplateFromFile("template")
                            .evaluate() 
                            .setTitle('My Title')
                            .setHeight(700)
                            .setWidth(1000)
                            .setSandboxMode(HtmlService.SandboxMode.NATIVE);

  return template

//  SpreadsheetApp.getActive().show(template);
};

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
};

function includeRaw(filename) {
    return HtmlService.createTemplateFromFile(filename).getRawContent();
}

而在我的 template.html 我有

<!DOCTYPE html>
<html>
    <head>
     <base target="_top">
      <?!= include('mystylesheet'); ?>
     <?!= includeRaw('Billets_JS'); ?>

   </head>
   <body> ...(more body)
      <select id="optionListYear" onchange="setFormList()">
         <option>Option 1</option>    
         <option>Option 2</option>    
      </select>
  </body>
</html>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
  function setFormList() {
    alert("In setFormList");
    MyNEwFunction();
  }

</script>

我还尝试了 JavaScript 文件的直接 include() 函数

Billets_JS 有这个:

<script>
    alert("Script included!");

// This code in this function runs when the page is loaded IF in the initial html file.
$(function() {

  alert("In the intial function");
});

function MyNewFunction() {
  alert("In My New Function");

}
</script>

我可以只加载脚本 ("Billets_JS") 来获取 HTML 文件。如果我有一个警报();此包含文件中任何函数之外的行,例如显示的行 运行s。所以我收到一个警告框,上面写着 "Script included!" 但不是 "In the initial function."

不过,我似乎无法以这种方式调用 MyNewFunction()。我使用了 Code.gs

中的两个包含函数

有没有什么方法可以加载 运行 的脚本而不将其全部放入初始加载的文件中?只需将函数移动到初始加载的文件即可,但我宁愿将它们分开。

您的问题是由于加载 JavaScript 个脚本的顺序造成的;由于 Billets_JS 依赖于 jQuery,它应该在 之后加载

简单移动:

<?!= includeRaw('Billets_JS'); ?>

紧接着出现:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>

如果您想主动解决这个问题,您可以在 Billets_JS 脚本的顶部检查 jQuery 的可用性,如下所示:

if (typeof jQuery == 'undefined') {  
    alert("No jQuery");
}