Blog posts from JavaScript (#javascript)
An imperative way to build a website!
(#_ )! This tutorial is definitely inspired by an interesting discussion in choosing a web tech stack in 2024. Of course, Imperative HTML is a more esoteric way of writing websites but still easy to learn for (#- )! Have you ever: Built arcane user interface with C/C++? Experienced in using Tcl/Tk (e.g. tkinter in Python)? Rejected the singularity of XML-based files (including QML and XAML) in user interface development? HTML itself was primarily based on XML (up to HTML 4.x). And we really hate if we have to write just to display the text “Hello, World!” this way: <!DOCTYPE html> <html> <body> <p>Hello, World!</p> </body> </html> Like, there’s no main function there. And when you wanted to make these elements interactive, you have to deal with the mess of document.getElementById()? A “Hello, World!” to Imperative HTML. Imperative HTML is technically JavaScript in disguise of a HTML <script> tag. But what makes Imperative HTML different than Node.js-like “back-end JavaScript programming” is that this still produces valid HTML, and even could prevent syntactic HTML errors just because you forgot to put your right bracket or double quotes in the perfect place. Or in other words, an Imperative HTML program webapp programmable webpage like this: <!DOCTYPE HTML> <script> function main() { let text = document.createElement("p"); text.className = "text-lg"; text.textContent = "Hello, World (>_ )!"; document.body.appendChild(text); } window.onload = main; </script> is definitely safer to write than: <p class="text-lg>Hello, World (>_ )!</p> <!-- Oh no, you didn't escape the > in (>_ )! --> <!-- ...and the missing double-quotes! --> Imperative HTML is powered by JavaScript, so you can still benefit from JavaScript’s tighter error-checking than regular HTML, where browsers attempt to guess the meaning and purpose of some HTML and CSS attributes, also known as quirks mode, because of legacy reasons. And since it is powered by JavaScript, the political dignity of "Imperative HTML" itself can be raised in two ways: By declaring that unlike HTML, Imperative HTML is a true programming language, full with Turing-complete selection and repetition control structures (#- ); By giving web developers more power to fight against people who are campaigning against JavaScript, especially for political reasons. Who knows that Imperative HTML gives devs more freedom to do so (#o )? And of course, you can slap on the power of TypeScript, if you really can, to ensure that you’re writing HTML tags and appropriate styles in a standards-compliant way. Isn’t this also a benefit of React’s JSX and CSS-in-JS? Imperative HTML is the intended way. This statement is controversial, of course, but the original XML-like HTML truly feels like the conventional way to write proper websites, yet our reinhart1010.id and alterine0101.id websites are still written in that conventional way. But remember, web browsers are still tasked to parse these HTML tags and convert them into internal structs which make up the today’s Document Object Model (DOM). Having to learn that HTML tags are objects would never be easier without attempting to learn how to declare HTML tags in the object-oriented way. Not to mention React, some of the world’s most loved web frameworks, still renders your elements this way. Since React features a Virtual DOM by default, they have to re-render the hand-crafted HTML JSX elements in the same way of this imperative tutorial: document.createElement() and so. So far, the only main disadvantage of Imperative HTML is that these webpages will not be good for SEOs, because the document is no longer written in machine-readable format (note: we can still leave some metadata inside <head> before <script> in Imperative HTML), causing JavaScript performance overhead, yadda-yadda, and so on. But the main irony is that even modern HTML scraper and parsers like BeautifulSoup parses regular HTML into objects the same way as browsers do, so imperative programming should be the way, right? Just right to the tutorial! In Imperative HTML, you (still) write code inside a HTML file, but you have to set up a few tags to make the web browser know that you're writing Imperative that supports HTML5: <!DOCTYPE html><script> // Your code here... </script> The ending </script> tag is optional, just like the ?> part of PHP scripts, but we highly recommend it as part of our coding convention. The main() function shown earlier is actually optional, but also recommended to ensure that the function is properly executed after the web browser is ready to load (using window.onload = main;. Declaring a HTML tag The usual way to write a HTML content is to use one of its supported tags, then adds attributes, <p id="hero-text" class=""> Hello, World (&gt;_ )! </p> The p is the Element Name, id and class is just some of the attributes, and the final, Hello, World (>_ )! text is the textContent. In Imperative HTML, it is just as easy as this: // Make sure you have put this code after the <script> tag! let text = document.createElement("p"); text.className = "text-lg"; text.textContent = "Hello, World (>_ )!"; document.body.appendChild(text); But if you love to explicitly declare the class, you can use this instead: // HTMLParagraphElement only applies to <p> tags. let text = new HTMLParagraphElement(); text.className = "text-lg"; text.textContent = "Hello, World (>_ )!"; document.body.appendChild(text); In Imperative HTML, you can assign event triggers even before attaching it to the page! // Create a button element that prints the sentence on click let btn = document.createElement("button"); btn.textContent = "Click Me!"; btn.addEventListener("click", function(e) { alert("Hello, World (>_ )!"); }, false); Displaying tags into the webpage And now, the most important part of this is to render these elements into the web browser. Now, our simplistic HTML structure of: <!DOCTYPE html><script> // ... </script> will be very likely to be rendered as this in most web browsers: <!DOCTYPE html> <html> <head> <script> // ... </script> </head> <body></body> </html> We can see that HTML has the <head>, the place to put the webpage's metadata, and <body>, the actual content displayed in the web browser. As a quick reference, Use document.head or document.body to modify the <head> or <body>, respectively These two parts are still considered as HTMLElements, which means you can use .appendChild() to append the element child (e.g. add new item to a HTML unordered list / <ul> / HTMLUListElement) Just like clear() to clear the Terminal console in other programming languages, you can use document.body.textcontent = "" to clear out the contents in the entire page. Now, using the interactive button example, we can simply add them into the webpage using the following code: <!DOCTYPE html><script> function main() { // Create a button element that prints the sentence on click let btn = document.createElement("button"); btn.textContent = "Click Me!"; btn.addEventListener("click", function(e) { alert("Hello, World (>_ )!"); }, false); // Attach them to the webpage document.body.appendChild(btn); } // Attach the main function when the webpage is ready to load! window.onload = main; </script> Well, I think that's all for now. Of course, there will be many interesting ways to use Imperative HTML, so stay tuned and follow us! 🩷
Re: The (extremely) loud minority (of JavaScript and Typescript developers)
Actually, there’s a DEV.to post named “17 Compelling Reasons to Ditch TypeScript for JavaScript”, only to be defeated by another post named “18 Reasons to Use TypeScript Since Yesterday”. I’ve documented all my criticisms here at “Code, not Content”. Since you specifically mentioned Twitter as the main source for these loud posts, I can say that many of them are just wanted to verify their status as a TS developer. I also see many of them ended up freelancing or worked on tech startups, which aren’t included in W3Techs list. When it comes into the big web industry, WordPress might won the “icing on the cake” by being able to afford a simple (despite themes and plugins are making it more complex), open CMS for managing content. Even many global news websites are still using that instead of fancy SPA. But successful stories, as told by the top ones who are using TypeScript, convinced people that every website should be rewritten in TypeScript. That's unfortunate, especially when simpler solutions do exist. For devs, code might be important, but for people, content matters.
Error 404 when using GitHub when I reload the page
This question was originally asked on StackOverflow. View original question I am making an E-commerce website with react and I upload the website to Github pages the deployment works ok, but when I click the Nav buttons to go to different parts of the webpage and reload the page, an error 404 appears: Failed to load resource: the server responded with a status of 404 () In the local host it works totally fine. Should I need to deploy my website as a new project again? I have always upload the websites the same way and I did not have this problem. I actualized my google browser, can there can be a compatibility problem? Thanks a lot! Note: I assume that you are using create-react-app with JSX and react-router-dom like this: <BrowserRouter> <Routes> <Route exact path="/" element={<HomePage />} /> <Route path="cart" element={<CartPage />} /> <Route path="settings" element={<SettingsPage />} /> </Routes> </BrowserRouter> Well, HTTP routing in GitHub Pages works differently than using the npm start command in your local machine. And fortunately, the developers behind create-react-app have already explained the technical reasons behind this: If you use routers that use the HTML5 pushState history API under the hood (for example, React Router with browserHistory), many static file servers will fail. For example, if you used React Router with a route for /todos/42, the development server will respond to localhost:3000/todos/42 properly, but an Express serving a production build as above will not. This is because when there is a fresh page load for a /todos/42, the server looks for the file build/todos/42 and does not find it. The server needs to be configured to respond to a request to /todos/42 by serving index.html. And yes, GitHub Pages also counts as a static file server, and expects that those routes are available as individual static files (e.g. build/cart.html for the /cartroute), and the goal here is to trick GitHub Pages to serve index.html instead for all of these routes. However, it is currently notpossible to fix this issue on the GitHub Pages' side, e.g. by applying the .htaccessconfiguration file (since GitHub Pages doesn't use Apache Web Server) or going to the repository settings on GitHub. So, what can be done here? The above code snippet uses <BrowserRouter>, which is known to be incompatible for hosting with GitHub Pages. And good news, many recommend to replace the <BrowserRouter> into <HashRouter>,which should work in practically all static file servers (see technical reasons here). There's a dedicated FreeCodeCamp article on how to set up <HashRouter> for your React project and publishing it into GitHub Pages. Note: Once you have replaced it with <HashRouter>, you will need to take care of existing hardcoded paths in HTML/JSX tags as <HashRouter> uses good-old HTML anchor/ID tags (e.g. #menu). That means <a href="/cart"> in your React app must be replaced with <a href="#/cart"> (Note the additional hash/# character there) or else it will again return a 404.