Web Project Structure - Can I nest server file in HTML file? - javascript

I'm fairly new to web development, but I've take a couple hands-on introductory courses where the basic structure of a website is you have an HTML file (or several ejs template files), a CSS file, and then you have something called a "server" file which is a JavaScript file, typically called app.js
I know that if I wanted to, I could include all my CSS inside the HTML file in <style> tags. My question is, should I have the need to do so, would it be possible for me to include the server code in <script> tags within a single HTML file?
Debating on whether or not I should put forth the effort to attempt to do so, but if it's generally problematic (note: I don't car about "best practice") for some reason such as it prevents you from working with certain packages/modules like EJS or Node.js then I will likely conclude that it doesn't make sense to try. As a novice web developer, I fear I am not aware of certain restrictions that I would likely run into if any (besides lack of module support).

would it be possible for me to include the server code in <script> tags within a single HTML file?
No.
Web browsers, which execute the scripts in webpages, do not provide JavaScript programs with the APIs required to run a server.
If you want to write a web server in JavaScript then you'll need to run it using a tool like Node.js and not a web browser.

No, you cannot put server-side code in HTML or in JS files that are sent to the client. Server-side code is code that is run on a server that you host, while client-side code is code that is run on the computer of the person who is visiting your webpage.
You can put client-side code in HTML <script> tags., and you can also include client-side code in separate JS files. The drawbacks are immense though, as:
Code highlighters won't be able to highlight your code and point out things like syntax errors as easily.
You won't be able to use tools like Babel and TypeScript, which input and output JS files.
You can't use NPM modules without a bundler like Webpack, which itself will output JS files.
Overall, there isn't really a good reason to use the <script> tag. It takes 2 extra seconds to just create another file for your JS, and it's more organized, more modularized and easier to use with external tools.

Related

How to reuse a single JavaScript in both server and client components of G Suite Add-on?

I have a JavaScript file that's a generated parser (let's call it MyParser), which I am using in an add-on for Google Forms.
It needs to be used in the client side's Sidebar.html where I'm including it with HtmlService.createHtmlOutputFromFile('MyParser.js').getContent();, which means it must be an .html file as far as I understand. Then it must be used on the server side where I have it in a file MyParser.js.gs.
With my current solution, it's duplicated in my file structure:
Code.gs
MyParser.js.gs
MyParser.js.html
Sidebar.html
Is there a way I can make this work without having two files? Edit: As I understand it, libraries are only for the server side.
If not, any hints to making the updating of the two files more robust (currently it's manual copy/paste)?
Edit: According to the best practices, one must wrap the JavaScript inside a <script> tag inside the .html file:
Notice that the included files contain <style> and <script> tags because they're HTML snippets and not pure .css or .js files.
So it seems it's not easy to have just one file.
As far as I could tell, there's no way to reuse a single file and respect Google's best practices.
My solution, following #tehhowch's advice, was with #google/clasp and doing local development.
To build the parser (in another GitHub project), I use npm-run-script. So, I just appended a && bash makeHTML.sh to the build script.
Inside makeHTML.sh I wrapped the built MyParser.js file in a <script> tag with:
#!/usr/bin/env bash
{ echo "<script>"; cat MyParser.js; echo "</script>"; } > MyParser.js.html
Since I'm using bash it's not a true node.js solution (won't run unless there's bash installed). If someone knows of a better way to pull off the wrapping that's 100% node and doesn't require installing a whole bunch of other modules, feel free to edit the answer.
As your add-on has just few files you might use ScriptApp.getResource(filename).getDataAsString() to get the content of a .gs file and add it to the sidebar HttpOutput object enclosed in <script> tags.
Code.gs
function showSidebar(){
const htmlOutput = HtmlService.createHtmlOutput('<h1>My Sidebar content</h1>');
.append(`<script>${ScriptApp.getResource('JavaScript').getDataAsString()}</script>`);
SpreadsheetApp.showSidebar(htmlOutput,'My Sidebar');
}
JavaScript.gs
To keep things simple, this file should contain only reusable (server-side + cliente-side) JavaScript
function myFunction(){
console.log('My function ran successfully');
}
The above over simplistic code example might be applied to a bit more complex projects and will keep you away from having to use CLASP.
Contrary as happens with .gs and .html files, so far I was unable to make ScriptApp.getResource(filename).getDataAsString() to work to pull reusable JavaScript from .gs files hosted on a Google Apps Script library. Anyway, it's still possible to stay away of CLASP, one option might be to use Advanced Service Google Apps Script API, another might be to host the shared JavaScript and imported from Google Drive or from another host by using Url Fetch service.
Related
Is it possible to read the contents of a Google Apps Script from another Script
HTML and JavaScript from another server?
Server side HTML Form validation?

uglifyjs javascript inside php files

My project has a lot of JS code inside PHP files. I want to minify the JS code in these files and I like the uglifyjs2 program. Is it possible for that (or any) JS minifier to act on JS code INSIDE a php file?
Someone is going to suggest removing all JS code from the PHP files and placing it in .js files - but that isn't always practical.
Keep in mind that I do NOT wish to minify the JS on the fly (acting on the output of the PHP interpreter). I am delivering PHP code to customers containing JS, and I wish to minify the JS inside the PHP files that I am delivering.
What you're looking for does not exist.
The only real reason to have inline JavaScript inside your PHP files is because you need to interpolate PHP and JavaScript in order to dynamically generate some or all of the script. You cannot reliably minify such JavaScript before the PHP is actually processed, so you'd be looking at minifying it after the PHP is run, on every request. There should be very little value to this, as the vast bulk of your JavaScript should not be written inside your PHP files.
Whatever the php script generates as output is sent to the browser. If you sent the "actual" output of the script instead of the output stream to another application and fetch and redirect that output - yes, you can do just anything.
Another question is how feasible and reasonable that approach is. uglifyjs2 is a node.js appliation, and therefore this step would require some kind of interprocess communication, i.e. extra-complexity and extra time/memory/points-of-failure and all that good stuff.
Maybe it's worth the effort, maybe not. Maybe something like https://github.com/tedious/JShrink will suffice...

Which program to use when running javascript code made in notepad

Ok, recently I started doing some tutorials in javascript. Soon I had finished doing some coding on notepad, saved it as " .js" but when I tried to open it I could not find a suitable program, hopefully, soomeone can tell me a method of running the code.
The first thing I did was try and download java, but quit the installer after seeing the ad based installer including vosteran, a web browser hijacker which I have had some experience with. Finally, is it necessary to download notepad ++ for this?
Thanks
It seems that you don't have a clear understanding of JavaScript and how it interacts with HTML. Java and JavaScript are two complete differently languages.
.js files are usually linked within a .html file or some server side language file, i.e. .php, .aspx. And the HTML file is opened with your browser, for example, Internet Explorer, Google Chrome or Firefox.
You should include the .js file in your HTML file using:
<script src="yourscript.js"></script>
Within the HTML file you can then invoke the methods and use the variables declared in your custom .js file.
You run js files in a webbrowser. Include files between tags.
Example:
There are two main options of running Javascript
1 In the browser
2 Or as a process
Choosing which one depends on your code. Please post an example of a what you are working on.
If your code fits option 1, then you will just need a small HTML file that includes reference to your javascript file.
If your code is not meant for a browser, you will likely need to install Nodejs. This is a CommonJS implementation of server-side js.
A note on Java and Javascript. They are in no way related. Netscape licensed the name from makers of Java and renamed language to Javascript in hopes it would inherate some of Java's popularity.

What are those cache.js and compilation-mappings files

Recently I received a package with web page. I see inside (beside normal html and js files) there are some JS files. It looks like this:
4A3674A3247236B3C8294D2378462378.cache.js
FE728493278423748230C48234782347.cache.js
compilation-mappings.txt
Inside .js files I see Javascript which is obfuscated or minified. Inside compilation-mappings.txt the cache.js are referenced. Are these files generated by some kind of WEB IDE? Unfortunately I have no chance to get information how this wep page was developed.
That is a web project coded in Java and compiled to JS using the GWT project tools.
GWT compiler does a lot of the work you would have to do manually when coding JS by hand, and some other tasks which are almost impossible in a normal JS project: obfuscate, compress, death-code removal, different optimization per browser, renaming of the scripts, code splitting, etc.
What you have in your app is the result of this compilation:
First you should have a unique index.html file, because GWT is used to produce RIA (Rich Internet Applications) also known as SPI (Single Page Interface).
The unique html file should have a reference to a javascript file named application_name.nocache.js. Note the .nocache. part, meaning that the web server should set the appropriate headers, so as it is not cached by proxies nor browsers. This file is very small becaust it just have the code to identify the browser and ask for the next javascript file.
This first script knows which NNNN.cache.js have to load each browser. The NNNN prefix is a unique number which is generated when the app is compiled, and it is different for each browser. GWT supports 6 different browser platforms, so normally you would have 6 files like this. Note the .cache. part of the name, meaning that this files could be cached for ever. They are large files because have all the code of your application.
So the normal workflow of your app is that the browser ask for the index.html file which can be cached. This file has the script tag to get the small start script applicaton.nocache.js which should be always requested to the server. It has just the code for loading the most recent permutation for your browser NNNN.cache.js which will be downloaded cached in your browser for ever.
You have more info about this stuff here
The goals of this naming convention is that the next time the user goes to the app, it will be in cache the index.html and NNNN.cache.js files, asking only for the application.nocache.js which is really small. It guarantees that the user loads always the most recent version of the app, that the browser will download just once the code of your app, that proxies or cache devices do not break your app when releasing a new version, etc.
Said that, it is almost impossible to figure out what the code does inspecting the javascript stuff because of the big obfuscation. You need the original .java files to understand the code or make modifications.
I can't say for sure, but often a string will be attached to the name of a javascript file so that when a new version is deployed clients will not use a cached version of the old one.
(ie, if you have myScript.js and change it, the browser will say "I already have myScript.js, Idon't need it. If it goes from being myScript1234.js to myScript1235.js the browser will go fetch it)
It is possible the framework in use generated those files as part of it's scheme to handle client side cache issues. Though without knowing more details of what framework they used, there's no way of knowing for sure.

Can we use any type of javascript code as a external .js file or sometime it's necessary to place in <head>?

Can we use any type of javascript code as a external .js file or sometime it's necessary to place in <head>?
The only time you would ever need to inline a js function in your HTML using the <SCRIPT> tags is if your javascript is generated by your server side program depending on the data, user settings etc.
Even this case is extemely rare as as you should be able to create a .js function whose behaviour is controlled by passing parameters.
Apart from keeping everything tidy and in the place where you expect to find it, there is a network performance advantage in that *.js files are cached on the client side so you are not constantly sending the same stuff over the network again and again.
Unless it is a Dynamic content which is placed by the server side scripts (very rarely used as there are many more better alternative methods) .. You can use JS in an external file ..
External js is re-usable .. I mean can be used by more than one HTML page .. So obviously it brings down the burden on browser ..
The site providing the live telecast or the NEWS/information (example:cricket scores etc) real-time examples for Dynamic content ..
You can place it all in an external file. It's much cleaner, and easier to maintain. It's a good practice to keep Javascript and CSS in their own external files. Do away with inline switching between CSS, HTML and Javascript for a much better organized project and less frustration down the road.
if using jquery then $.document.ready() is the way to go

Categories

Resources