I work on a Google Apps Script project with a *.gs-file and a *.html-file. I work in the browser on script.google.com
, so all these files are stored in my Google account. In the html file I have added some JavaScript in a <script>
-Tag as as well some CSS in a <style>
-tag.
I would like to separate the JavaScript and the CSS parts to separate files. They should also be stored in my Google account, and directly linked and easy accessible in my project.
When I click on File --> New the only options for adding files to the project are Google Apps Script or HTML. So it seems that this is not natively supported. But I would also be happy with a workaround, say to add some HTML file, write the JavaScript into that and linking it somehow.
My goal is just to have a better overview over the project, and in my main.html I do not want to get distracted by JavaScript or CSS.
Similar questions have been asked before here, but it seems that they are all about linking external JavaScript files, which is not what I want.
To add your CSS and JavaScript code to the Google Apps Script project, create an HTML file as instructed in the best practices doc from Google. Example taken from the referred page:
For the server-side code, use .gs file.
function doGet(request) {
return HtmlService.createTemplateFromFile('Page')
.evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Use an .html file for the HTML code. Note: The code below uses scriptlets, which set the place where the CSS and JavaScript should be inserted.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('Stylesheet'); ?>
</head>
<body>
<h1>Welcome</h1>
<p>Please enjoy this helpful script.</p>
<?!= include('JavaScript'); ?>
</body>
</html>
For CSS, create an .html file. Put the CSS inside style
tags.
<style>
p {
color: green;
}
</style>
For JavaScript code, create an .html file. Put the JavaScript code inside script
tags.
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
Another way is to use the Drive Service, the Drive Advanced Service or the URL Fetch Service to get the JavaScript code from a file hosted elsewhere.
Related