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 is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻