Load External JavaScript Libraries in Google Scripts with eval()
You can include external JavaScript libraries or any other script in your Google Apps Script projects in multiple ways.
The best option would be create a new script (.gs) file inside your Google Script and copy-paste the entire JavaScript code into the file. This makes it easy for you to debug the code right inside the Apps Script IDE.
Alternatively, you can create a new HTML file inside apps script, copy-paste the code inside that file and use the eval()
method as shown here:
function loadJSFromHTMLFile() {
var javascript = HtmlService.createTemplateFromFile('script.html').getRawContent();
eval(javascript);
}
If the JavaScript file is on a remote server or your Google Drive, you can use the UrlFetchApp and Drive.getFileById()
method respectively to import the script into your Google Script at execution time.
// Load JavaScript from External Server
function loadJSFromServer() {
var url = 'https://example.com/script.text';
var javascript = UrlFetchApp.fetch(url).getContentText();
eval(javascript);
}
// Load JavaScript from Google Drive
function loadJSFromGoogleDrive() {
var rawJS = DriveApp.getFileById(id).getBlob().getDataAsString();
eval(rawJS);
}
Finally, if you need to load multiple JavaScript libraries from a remote CDN, this technique by @BriaEgan will be useful. It creates the variables in the global namespace.
// Credit Brian @github
var LIBRARIES = {
prettyDate: 'http://ejohn.org/files/pretty.js',
underScore: 'http://underscorejs.org/underscore-min.js',
};
Object.keys(LIBRARIES).forEach(function (library) {
newFunc = loadJSFromUrl(LIBRARIES[library]);
eval('var ' + library + ' = ' + newFunc);
});
function loadJSFromUrl(url) {
return eval(UrlFetchApp.fetch(url).getContentText());
}
eval()
is found to be slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines.
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory