Karl_S Karl_S - 1 year ago 130
jQuery Question

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

I have a Templated HTML file I am loading and can load other HTML using the functions as shown in the code below. I am trying to get included functions to run in the script tags. This is an HTMLService in a Google Sheet script.

In Code.gs I have

function doGet() {
var template = HtmlService.createTemplateFromFile("template")
.setTitle('My Title')

return template

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

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

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

And in my template.html I have

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

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

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


I have also tried the straight include() function for the JavaScript file

Billets_JS has this:

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");


I can get the HTML file with only script ("Billets_JS") to load. If I have an alert(); line outside of any functions in this included file, such as the one shown, the line runs. So I get an Alert box stating "Script included!" But not the one for "In the initial function."

I cannot seem to call MyNewFunction() this way, though. I have used both Include functions found in Code.gs

Is there any way to load script that will run without putting it all in the initally loaded file? Simply moving the functions to the intially loaded file works, but I would rather segregate them.

Answer Source

Your problem is due to the order of loading JavaScript scripts; since Billets_JS depends on jQuery, it should load after it.

Simply move:

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

to appear right after:

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

If you want to be proactive about this, you could check for the availability of jQuery at the top of your Billets_JS script, like this:

if (typeof jQuery == 'undefined') {  
    alert("No jQuery");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download