So far I used bare browser APIs to manipulate the frontend. This is no way to write frontend code, so over the next few episodes I'll be using a lot of different frontend frameworks.
Starting with the much beloved classic jQuery. Rumors of jQuery's deaths have been vastly exaggerated, it's still used by 80% of the website on the internet, and it will surely outlive us all. Unless we solve aging and live forever.
Install jQuery
As I mentioned before, we do not want to use CDN to load jQuery, or anything else for that matter - all our resources should be bundled with our app if possible.
$ npm install jquery
We can copy all assets from previous episodes except for the app.js
script.
Load jQuery
It works just like it did with D3, just one extra line before our app.js
script:
<script src="./node_modules/jquery/dist/jquery.js"></script>
jQuely app.js
And now we can rewrite DOM manipulations in jQuery. It's both more concise, and more readable.
function appendInput(command) {
let e = $(
`<div class='input-line'>
<span class='prompt'>$</span>
<span class='input'></span>
</div>`)
e.find('.input').text(command)
$("#history").append(e)
}
function appendOutput(output) {
let e = $(`<div class='output'></div>`)
e.text(output)
$("#history").append(e)
}
$("form").on("submit", function(e) {
e.preventDefault()
let command = $("input").val()
let output = window.api.runCommand(command)
appendInput(command)
appendOutput(output)
$("input").val("")
$("input")[0].scrollIntoView()
})
Security
Now it would be tempting to use direct string interpolation and just type <span class='input'>${command}</span>
, but that's insecure, and the app would behave incorrectly if command or output contained special characters like <
or >
- which shells use all the time, even if for something different than HTML.
There are other ways to be even more expressive, and secure, without using bundlers - such as tagged template literals and various template libraries like handlebars.
The choice is yours, even more so that with a normal web apps, as Electron really doesn't care what you use for the frontend part, and you know exactly which browser you'll be using as you're bundling it with the app.
Result
It looks just like previous two episodes, but let's make some new screenshots anyway:
In the next episode we'll get some fancy Google Fonts for our terminal app. Then we'll get to the bundlers.
As usual, all the code for the episode is here.
Top comments (1)
It's a bit of a myth that "x% of the sites still use jQuery". The fact is that jQuery is still used by a lot of trackers and intrusive marketing scripts. Typically added by SEO or marketing people. So technically you'll find it in a lot of sites. But the sites themselves are not built with jQuery, it will be React or whatever is fashionable. It's a bit like COBOL in the finance world.