Import minified JavaScript code into HTML file without pasting in - javascript

I have an SPA and adding newrelic analytics to the project. Newrelic provided me with a script tag with a bunch of minified code. I do not want to paste it in the html file because i can't use env variables, and it convolutes our html file. What would be a good way to import it as a script without pasting it in the file? i tried pasting it into a file and referencing it but not entirely sure if that is a good way to go about it.
In essence, instead of using
<script>
window.NREUM||(NREUM={}),__nr_require=function(t,e,n){function r(n){if(!e[n]){var o=e[n]={exports:{}};t[n][0].call(o.exports,function(e){var o=t[n][1][e];return r(o||e)},o,o.exports)}return e[n].exports}if("function"==typeof __nr_require)return
</script>
I want to do something like the following based on an env variable
<script src="/src/analytics/newrelic"></script>
Any advice would do.

Loading the New Relic Browser agent from an external file is not supported:
Link: Browser Instrumentation
It may work, but if you encounter any problems, the first thing the support engineers will ask is how you are deploying the agent.

Related

Autocompletion for VSCode for a module imported via <script src>

Issue description
I would like to have Visual Studio Code to hint autocompletion and provide documentation for a JavaScript project which includes libraries a module in a separate HTML file.
Context
I am using P5JS. It assumes we include the P5JS library and our script via the <script src="…"> tag in an HTML file. Autocompletion and documentation work after installing the p5.vscode extension. So, no problem here.
I am also using ml-matrix, which I'm including in the HTML via the <script src="…"> tag. The library constructors and methods can be accessed via mlMatrix.. (I figured this by toying around in the console, and I wouldn't know otherwise how to find out I need to prepend mlMatrix. to all functions in the library.)
index.html
<head>
<!-- script src="…" P5JS libraries -->
<script src="./node_modules/ml-matrix/matrix.umd.js"></script>
</head>
<body>
<script src="./script.js"></script>
</body>
script.js
A = mlMatrix.Matrix.eye(3) // no autocompletion or docs, code runs
console.log(A)
Workaround
Adding import * as mlMatrix from "ml-matrix" to the beginning of script.js makes autocompletion and documentation work, but the overall project does not run. So, I have to comment and uncomment the first line every time I save and preview my edits on the browser.
script.js
import * as mlMatrix from "ml-matrix"
A = mlMatrix.Matrix.eye(3) // autocompletion and docs work, code doesn't run
console.log(A)
When loading the HTML, the browser complains with script.js:1 Uncaught SyntaxError: Cannot use import statement outside a module..
Desiderata
I'd like to be able to save and preview my project while having a working autocompletion and documentation hint from VSC.
Debugging
After reading a few sections of David Flanagan's «JavaScript: The Definitive Guide», I started figuring out what's going on. So, I'm reporting here my current understanding.
JavaScript, or rather ECMAScript, used to be a scripting language.
Scripts loaded with <script src="…"> are "global" scripts, living on the current page, injecting vars and functions in the global scope (or window object).
In order to support proper software engineering relying on modularity, modules were introduced in 2015, in ECMAScript 6, or ES6 in short. To import a module in an HTML document one can use <script type="module" src="…">.
Now, to import a module in a JS file, the file itself needs to be a module. So, dealing with an actual script myself, I cannot do such a thing.
Even by <script src="…"> a module, it won't inject itself in the main namespace. It will create a whatever name where it will store everything it exports. So, now we are at the point where we need to instruct the IDE that a module has been loaded on the HTML side with a specific name and it's used in a JS script.
So, we have now a more articulate question.
Issue re-statement
How to inform VSC that a module has been loaded through the HTML page?
I believe a probable answer will include some custom jsconfig.json to be created. Right now I have zero clues about how to do this.
Another solution would be using some specific ///<reference path="…"/> at the beginning of the JS file. Also for this I have no specific knowledge.

Eleventy, Nunjucks, Tailwindcss, javascript toggle function to hide and display content

i have a static site using eleventy, tailwindcss, and nunjucks. this is my first time and overall really like it, but i still find the layout a bit confusing.
i would like to create a page of reusuable components, each component with two parts. example display of component,and then below it a div containing the components code to copy and paste.
in my /src/utils/ directory i added a simple toggle function to add and remove the class 'block' (tailwindcss)
i dont understand how to access that function in my /src/site/components.njk files code to add the functionality to my page.
numerous and lengthy google and duck duck go queries have not returned much info, so any and all help is appreciated
Since you want to have that functionality client-side, you need to make sure that your JavaScript is included in your site output. Since your /src/ directory only exists in your repository, it won't be available to the browser after your site has been built. The easiest way to make it accessible to the browser is to copy the JavaScript file to your output directory, then include it as a script in your HTML output. Make sure the URL matches the output location. For example, if your source file is /src/utils/component-toggle.js, your output directory is /dist/ and you copy the file to /dist/utils/component-toggle.js, the script tag should look like this:
<script src="/utils/component-toggle.js" defer></script>
See Passthrough file copy to learn how to copy static files during your build step.
Make sure your JavaScript file works in a Browser context as well. For example, you can't use CommonJS (module.exports and require() syntax), since it's a NodeJS concept and doesn't exist in Browsers. If you use ES Module syntax (export default {} syntax), make sure it's supported in all browser your site supports.
I've recently written a longer answer regarding this topic which explains why you have to do it this way as well as the difference between build-time and run-time JavaScript for static site generators, you can read it here if you want to know more.

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

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.

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?

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.

Categories

Resources