Thursday, January 13, 2022

subjective notes about Google Apps Script

Some thoughts after the last few months working with Google Apps Script

  1. It's far easier to write standalone Google Apps Scripts (GAS) - from Google Drive as New - More - Google Apps Script or from an existing Google Doc or Sheet from Menu - Extensions - Apps Script rather than creating php scripts which call the Google APIs. There are multiple reasons, like 
    * better documentation with example code
    * excellent third-party examples 
    * all the details of setting up an appropriate project, granting scopes etc are simplified, especially using classes like DriveApp, DocumentApp and so on.  

  2. One of the disadvantages of these standalone GAS is they usually have a three to five second (approx) response lag when fetching data from a google sheet or elsewhere, probably due to new server connection, sanitizing, security checks etc. So, AJAX calls are recommended for a better user experience if using the scripts inside iframes.  

  3. Another disadvantage would be the long urls which are not on our domain, but that can be worked around by encapsulating inside an iframe on our site as above. For this, we should remember to set the Sandbox mode to IFRAME.

  4. Script execution slows down dramatically if html is being generated in a loop. Especially when each loop execution has several API calls. For example, the following code snippet takes around 10 seconds to execute for 20 matches - 
    while (imgfiles.hasNext()){ count++; if (count > 20) { // to add paging code here. break; } imgfile=imgfiles.next(); //if(imgfile.getName().indexOf(title)!=-1){ //Logger.log("Found: "+imgfile.getName()); // https://stackoverflow.com/questions/489340/vertically-align-text-next-to-an-image imgfilename=imgfile.getName(); imgfileid=imgfile.getId(); drivefile=Drive.Files.get(imgfileid); // https://stackoverflow.com/questions/61272952/how-to-get-a-link-of-the-thumbnail-of-a-google-drive-file-using-google-apps-scri html+='<div>'+count+'. '; html+='<img style="vertical-align:middle" src="'; // changing the size of thumbnail linkstr = drivefile.thumbnailLink; linkstr = linkstr.substring(0, linkstr.length - 3)+'350'; html+=linkstr; //html+=imgfile.thumbnailLink; html+='" title="'; html+=imgfilename; html+='" alt="'; html+=imgfilename; html+='" width="150" >'; html+='<span style=""> &nbsp; <a href="'+drivefile.webContentLink+'" target="_blank"> <button >Download</button></a></span>'; html+='</div>'; html+='<br>Title: '; html+=imgfilename; html+='<br>Description: '; html+=imgfile.getDescription(); html+=' <hr>'; }
    A better way to implement would be to do all the processing in the background and display asynchronously. Link to best practices.

No comments:

Post a Comment