If you write any Apps Script using HtmlService – and that’s pretty much everyone nowadays, you probably write client side JavaScript as Html files with <script> tags, and server side as .gs files.
But Apps Script is JavaScript, so why treat them differently? You also sometimes end up duplicating useful bits of code for .js purposes that you’ve already written once for .gs.
Here’s how to use the same code for both, or to write code intended to be run client side using the server side .gs IDE environment. Not only does this avoid duplication, it allows you to easily delegate compute intensive things to the client where they tend to run much faster.
Example
Let’s say I have a useful set of functions I’m using in .gs to generate unique strings, and I want to also do something like that with something I’m planning to do on the client side.
Here’s my web app. Nothing unusual here.
function doGet() { return HtmlService.createTemplateFromFile('clientHtml') .evaluate() .setSandboxMode(HtmlService.SandboxMode.IFRAME); }
Here’s my clientHtml file. There’s no JavaScript code, aside from a call to doTheClientWork();
<p> Sharing the same code both server and client side </p> <div id="client">client:</div> <div id="server">server:</div> <?!= requireGs (['usefulThings' , 'clientJs']); ?> <script> // and run it window.onload = function () { doTheClientWork(); }; </script>
Notice the templating of the requireGs() function. This is going to go off to pick up code that is being managed, and potentially used in the .gs server environment, and insert it into the client environment to be run there.
requireGs()
Here’s how it works. The ScriptApp.getResource() function returns a Blob that is the code for a .gs file. Using that we can inject it into the HtmlOutput stream, and reuse or manage all out client side JavaScript as if it were server side.
/** * given an array of .gs file names, it will get the source and return them concatenated for insertion into htmlservice * like this you can share the same code between client and server side, and use the Apps Script IDE to manage your js code * @param {string[]} scripts the names of all the scripts needed * @return {string} the code inside script tags */ function requireGs (scripts) { return '<script>\n' + scripts.map (function (d) { return ScriptApp.getResource(d).getDataAsString(); }) .join('\n\n') + '</script>\n'; }
So all you have to do is give a list in your html template of the scripts you’d like included to run on the client, like this.
<?!= requireGs (['usefulThings' , 'clientJs']); ?>
Client side
This code is expected to only run client side, but I’m managing it as a .gs file which means I can use the regular Apps Script IDE. The fact that it refers to things that don’t exist in apps script such as the document object is irrelevant, since we never actually execute it server side. Note that it runs the same function on both the client and the server.
/** * this is stuff I only want to run on the client, but I'll manage it with the apps script IDE */ function doTheClientWork () { // i'll call getUniqueString, which is shared between both client and server document.getElementById("client").innerHTML += generateUniqueString(); // and we'll run the same thing server side google.script.run .withSuccessHandler( function (data) { document.getElementById("server").innerHTML += data; }) .withFailureHandler ( function (error) { document.getElementById("server").innerHTML += error; }) .generateUniqueString(); }
Shared code
Here’s the code I want to be able to run both server and client side. Like this it only needs to exist in one place – as a .gs script file. For the purposes of this discussion, it’s not important what it does.
oh… and here’s the output

- 2 ways to create and preserve formulas with fiddler for Google Apps Script
- A fourth way to preserve and create formulas with Fiddler for Sheets, plus some more new methods
- A functional approach to updating master sheet with Fiddler
- A recursive extend function for Apps Script
- A third way to preserve formulas with fiddler, plus 2 new methods
- A webapp to share copies of the contents of folders
- Abstracting services with closures
- Add-on spinner
- Addressing namespace and library methods from google.script.run
- Anonymous user registration with the Apps Script PropertiesService
- Apps for Office – binding example comparison
- Apps Script as a proxy
- Apps Script const scoping problems
- Apps Script server side to client side htmlservice progress reporting using CacheService
- Calculating image dimensions in server side apps script
- Calculating the last day of a given weekday in the month
- Canvasser
- Chaining JavaScript
- Changing class properties dynamically
- Checking the argument types in Apps Script
- Cleaning up a document format
- Cleaning up heading levels
- Column numbers to characters
- Composing functions and functional programming
- Configurable canvas meter
- Convert JSON to XML
- Converting SVG to PNG with JavaScript
- Converting timestamps to dates formula
- Copying canvas and svg images from your Add-on
- Copying to new host location
- Copying to new host location
- Counting script and library usage
- Create sha1 signatures with apps script
- Creating a key digest to use for a cache key or to compare content
- Creating a pile of files list from Google Drive
- Creating and working with transposed sheet data arrays
- Cross Origin Resource sharing (CORS)
- CryptoJS libraries for Google Apps Script
- Custom checking for exponential backoff
- Data wrangling with named columns in Google Spreadsheet
- Dealing with objects that are too large for the property or cache store
- Detecting Spreadsheet tables automatically with Google Apps Script
- Direction minimizer – other usages
- Do something useful with GAS in 5 minutes
- Dynamically creating tables with clusterize.js
- EasyCron Library
- ES6 JavaScript features
- Exponential backoff
- Exponential backoff for promises
- Fiddler – A functional approach to fiddling with sheet data
- Fiddler and rangeLists
- Fiddler now supports joins to merge matching columns from multiple sheets
- Fiddling with text fields that look like dates
- Filling ranges in Google Sheets
- Finding a Drive App folder by path
- Finding where Drive hosting is being used in Sites
- Flattening an object with dot syntax
- Flattening and unflattening objects to spreadsheets
- Formatting GraphQL queries
- Formatting sheet column data with fiddler
- From notes to frequencies and back again
- From Xml to JSON
- Generating and managing random lists with JavaScript and Apps Script
- Generating coupon codes with expiry dates
- Generating test data for sheets and tables
- Get GAS library info
- Getting an htmlservice template from a library
- Getting insights into Sheets performance
- Google Drive as cache
- Header formatting with fiddler
- Highlight duplicate rows in a sheet – map and reduce
- Highlight duplicate rows in a sheet – map, filter and every
- How to determine what kind of object something is in Apps Script
- How to get stats about youtube videos in your channel with apps script
- How to pass non stringifyable objects to html service
- How to transpose spreadsheet data with apps script
- Identify duplicates on Drive
- Identifying hosted files
- Implementing a client side progress bar reporting on server side work for htmlService
- Importing Predictwise data
- Improved namespace pattern for Apps Script
- Including the stack in custom errors
- Iterator magic – Splitting an array into chunks
- JavaScript closures – how, where and why
- JavaScript currying and functional programming
- JavaScript currying and functional programming – even more
- JavaScript recursion primer
- JavaScript snippet to create a default method for an object
- JSONP and JSON and Google Apps Script webapps
- Loading large JSON datasets into BigQuery with Apps Script
- Logging differences in strings in Apps Script
- Measuring library load speed
- Migrating user and script properties
- Minimizing maps directionfinder api calls
- More client server code sharing
- More recursion – parents and children
- More sheet data fiddling
- Multiple inserts in Fusion Tables
- Namespaces in libraries and scripts
- Normalizing the header level of blank paragraphs
- Optimizing sheet formatting with Apps Script
- Optimizing showing and hiding rows and columns
- Organizing asynchronous calls to google.script.run
- Organizing parallel streams of server calls with google.script.run promises
- Parallel process orchestration with HtmlService
- Passing data to html service
- Patching site html
- Populating sheets with API data using a Fiddler
- Proxy jsonp
- Pseudo binding in HTML service
- Queuing asynchronous tasks with rate limit and concurrency constraints
- Random and fake test data in Sheets with Google Apps Script
- Recursive async functions
- Removing duplicate paragraphs
- Reporting file, function and line number in Apps Script
- Resumable uploads – writing large files to Drive with Apps Script
- Reusing html stuff between Apps Script projects
- Roughly matching text
- Serving apps script to JavaScript app
- Shortcut for adding nested properties to a JavaScript object
- Simple but powerful Apps Script Unit Test library
- Simple server side polling
- Sorting Google Sheet DisplayValues
- Squeezing more into (and getting more out of) Cache services
- Styling Gmail html tables
- Summarizing emails to a sheet
- SunCalc
- Super simple cipher library for Apps Script encryption and decryption
- TimeSimmer : An adjustable timer for apps that need to speed up or slow down time
- Transform dates for add-on transfer
- Transposing sheet data
- Traversing a tree
- Unique values with data fiddler
- Unnesting data to sheet values
- Untangling with promises
- Use Drive properties to find app files
- Use promise instead of callback for settimeout
- Using Advanced Drive service to convert files
- Using Apps Script for xml json conversion
- Using array formulas to improve performance
- Using crossfilter with Google Apps Script
- Using D3 in server side Gas
- Using es6 promises server side in Apps Script
- Using Es6 with Apps Script
- Using exponential backoff with github api – dealing with data “in preparation”
- Using Google sheets via Bigquery from Apps Script
- Using named locks with Google Apps Scripts
- Using promises to orchestrate Html service polling
- Using promises with apps script
- Using the Itunes API with Apps Script
- Using the slideshare API from Apps Script
- Using timing functions to get insight into Sheets
- Watching docs for changes
- Watching for server side changes from the client html service
- What JavaScript engine is Apps Script running on?
- Why Base64
- Zipping to make stuff fit in cache or properties service.
Why not join our community, follow the blog an or follow me on Twitter