Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a Web Page Directly from a JavaScript File Exclusively

I have the desire to do something that I've never seen done.

I'd like to create a web page using only client-side javascript. For example, I want to put a javascript file at www.webpage.com/index.js and have the browser run that javascript file. Within that file, I'll generate html and css, but I'd like the entry point to be exclusively that javascript file instead of HTML.

If this is not possible, I think it should be. Many times my html files are just a header, title and an empty body. When this is the case, it is silly that an html file has to be downloaded first, and then only after that can the browser download the javascript file that actually fills that empty body with content.

I realize that search engines may not know how to index pages where the html is generated by client-side javascript, but again, I say they should be able to do this and probably eventually will if they haven't already.

I've never seen this done. Is this possible? If so, can you please direct me to any resources covering the topic. I couldn't find anything.

like image 213
Lonnie Best Avatar asked Sep 10 '26 17:09

Lonnie Best


2 Answers

I've written many "pages" that are just

<!DOCTYPE html>
<html>
   <head><meta charset="utf-8"></head>
   <body><script>

// The real stuff goes here, as inlined Javascript
// No need to make an extra roundtrip to the server
let d = document.body.appendChild(document.createElement("div"));
d.textContent = "Hello, world.";

   </body></script>
</html>

So basically the only thing I place in the HTML part is a fix for a bad decision taken in the past (having the default encoding ISO-8859-1 instead of UTF-8). This kind of file is indeed just Javascript, with the minimal wrapping needed to have a browser loading and executing it.

like image 196
6502 Avatar answered Sep 13 '26 07:09

6502


As mentioned elsewhere, it's possible to create JavaScript that is also a valid HTML file.

<!-- --><script>
console.log('Hello, World!');
// </script>

This works because the JavaScript spec has

B Additional ECMAScript Features for Web Browsers

B.1 Additional Syntax

B.1.3 HTML-like Comments

...

SingleLineHTMLOpenComment ::
    <!-- SingleLineCommentCharsopt

like image 24
Mike Samuel Avatar answered Sep 13 '26 07:09

Mike Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!