This year I finally managed to complete an entry for the Binary Golf Grand Prix. It’s nothing fancy, just a quick take on a self-replicating HTML file. The challenge is to create a self-replicating file which must make one copy of itself, named the copy 4, not run that copy, and display or output the number 4. I figured a self-replicating HTML would be a good introduction to golfing, and seeing just how small I could get the file would be interesting, for sure.

My final result is a 123 byte file, which displays the number 4 in the browser, and downloads an exact copy of itself to a file named 4 in your downloads directory.

<body>4<script>d=document;f=d.createElement('a');f.href='data:;,<body>'+d.body.innerHTML;f.download='4';f.click();</script>

screenshot of sha256 hashes, file content and firefox browser

We are able to get this as small as it is by using the variable d to represent document at two places in the file, not specifying a data type in the download, and not closing the <body> tag. I am still hunting for other possibilities to shave off another byte or two.

UPDATE 07/17/23

After making this post and submitting this entry, I received a reply on Mastodon from @eater@cijber.social pointing out that I can remove some single quotes to remove a few more bytes. eater then proceeded to to take my entry and golf it down to around 94 bytes. I was already in bed at this point, but couldn’t stop thinking about it. I got out of bed and got back to work. After a few failed attempts at lowering the size of the script section of my file, I realize I could move some of the <a> tag outside of the script and assign it an id to manipulate from inside the script. I can then completely remove the body tag and only use the <a> and <script> tags. I can also reference the a tag id, replacing the innerHTML property with outerHTML to append the file contents to my href data proprty. The final result lowers my file size all the way down to 83 bytes.

<a download="4" id="f">4<script>f.href='data:,'+f.outerHTML;f.click();</script></a>

screenshot of sha256 hashes, file content and firefox browser of second entry

Huge thanks to eater for kicking my brain into high gear last night and for the collab, even if I didn’t have you send over your final result.