Interesting HTML, CSS and JS tricks

As a result, users call our numbers and report information that they wanted to pass on to the special services.

▍ Editable HTML pages

Button press

DesignMode ON/OFFmakes the web page editable

. All you need is one line of JavaScript in your code:

document.designMode = "on";

These ancient APIs appeared 25 years ago, but are still supported in browsers.

▍ Proper use of

In recent years, support for modern AVIF and WebP image compression formats has appeared in many browsers (unfortunately, December 10, 2022 Google

deleted

support for JPEG XL from Chromium, so this format is no longer very relevant). You can reduce traffic from your site if

enable this optimization

using the tag

<picture>

.

The idea is to only serve AVIF and WebP to browsers that support it.

  1. Converting images to another format. For example, using the cross-platform utility imagemagick or service avif.io.
    $ magick convert image.jpg image.avif

    We perform a similar conversion for each pair of formats (jpg/avif, jpg/webp).

  2. Instead of the traditional <img>write the tag <picture>, which allows multiple URLs to be listed for the same image. First we specify AVIF as the smallest format. Normal browsers will load it and Edge and all others that don’t support AVIFwill go further down the list: WebP and JPEG.
    <picture>
    <source srcset="https://habr.com/document.avif" type="image/avif">
    <source srcset="https://habr.com/document.webp" type="image/webp">
    <img src="https://habr.com/document.jpeg" alt="Скриншот" width="375" height="153" class="border">
    </picture>

    All options are indicated in the tag <source>and only the last one in the tag <img>.

  3. Known optimization for faster page loading – tweak HTTP/2 Server Push on the server so that resources are loaded immediately, without waiting for their request after HTML parsing. In our case, for the elements <picture> it is not optimal to load everything to the client. It is better to recognize the browser user agent and push the image of the appropriate format in advance. This field is specially designed for this. Accept in user-agent. For example, the latest Firefox sends Accept of this kind:

    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,/;q=0.8

▍ Storing application state in URL

If you have some kind of web application and you want to enable people to work in it

without authorization

on the site and storing data on the server, then there is an interesting hack for this:

save state in url

in the client browser.

This allows the user to “save” and later continue working (editing data). It is also convenient to share the results of work with colleagues simply by sending the URL.

The application state is a JSON file, it is encoded into a string, then compressed and translated into Base64 bytes, which are added to the URL after the characters `/g/a#`. For example, in this way:

наш_сайт.com/g/a#N4IgzgpgTglghgGxgLwnARgiAxA9lAWxAC5QA7X...

Pseudocode to implement such functionality:

const stateString = JSON.stringify(appState); // appState представляет собой объект JSON
const compressed = compress(stateString);
const encoded = Base64.encode(compressed);
// Пушим закодированную строку в url
// ...Позже при загрузке страницы или undo/redo читаем url и
// делаем следующее
const decoded = Base64.decode(encoded); // в той же кодировке, что и выше, но считывается из url
const uncompressed = uncompress(decoded);
const newState = JSON.parse(uncompressed);
// Загружаем приложение с новым состоянием newState

The URL is updated after each change in the state of the application, so you can copy the current state with a simple copy-paste from the browser’s address bar. Examples of How It Works: Interactive Flowchart Editors

knot end

And

mermaid live

:

There are several options how to implement the compression/decompression functions, for example, lz-stirng or pako.

As a bonus, we get “free” undo / redo functionality from the browser stack for our web application, as well as automatic injection into any third-party web page that supports embeds.

You can also see how Yahoo! Finance stores the user’s settings in the URL:

finance.yahoo.com

https://finance.yahoo.com/quote/F/chart?p=F#eyJpbnRlcnZhbCI6IndlZWsiLCJwZXJpb2RpY2l0eSI6MSwidGltZVVuaXQiOm51bGwsImNhbmRsZVdpZHRoIjo0LjM0ODY1OTAwMzgzMTQxNzUsImZsaXBwZWQiOmZhbHNlLCJ2b2x1bWVVbmRlcmxheSI6dHJ1ZSwiYWRqIjp0cnVlLCJjcm9zc2hhaXIiOnRydWUsImNoYXJ0VHlwZSI6ImxpbmUiLCJleHRlbmRlZCI6ZmFsc2UsIm1hcmtldFNlc3Npb25zIjp7fSwiYWdncmVnYXRpb25UeXBlIjoib2hsYyIsImNoYXJ0U2NhbGUiOiJsaW5lYXIiLCJzdHVkaWVzIjp7IuKAjHZvbCB1bmRy4oCMIjp7InR5cGUiOiJ2b2wgdW5kciIsImlucHV0cyI6eyJpZCI6IuKAjHZvbCB1bmRy4oCMIiwiZGlzcGxheSI6IuKAjHZvbCB1bmRy4oCMIn0sIm91dHB1dHMiOnsiVXAgVm9sdW1lIjoiIzAwYjA2MSIsIkRvd24gVm9sdW1lIjoiI2ZmMzMzYSJ9LCJwYW5lbCI6ImNoYXJ0IiwicGFyYW1ldGVycyI6eyJ3aWR0aEZhY3RvciI6MC40NSwiY2hhcnROYW1lIjoiY2hhcnQifX19LCJwYW5lbHMiOnsiY2hhcnQiOnsicGVyY2VudCI6MSwiZGlzcGxheSI6IkYiLCJjaGFydE5hbWUiOiJjaGFydCIsImluZGV4IjowLCJ5QXhpcyI6eyJuYW1lIjoiY2hhcnQiLCJwb3NpdGlvbiI6bnVsbH0sInlheGlzTEhTIjpbXSwieWF4aXNSSFMiOlsiY2hhcnQiLCLigIx2b2wgdW5kcuKAjCJdfX0sInNldFNwYW4iOnsibXVsdGlwbGllciI6NSwiYmFzZSI6InllYXIiLCJwZXJpb2RpY2l0eSI6eyJwZXJpb2QiOjEsImludGVydmFsIjoid2VlayJ9fSwibGluZVdpZHRoIjoyLCJzdHJpcGVkQmFja2dyb3VuZCI6dHJ1ZSwiZXZlbnRzIjp0cnVlLCJjb2xvciI6IiMwMDgxZjIiLCJzdHJpcGVkQmFja2dyb3VkIjp0cnVlLCJldmVudE1hcCI6eyJjb3Jwb3JhdGUiOnsiZGl2cyI6dHJ1ZSwic3BsaXRzIjp0cnVlfSwic2lnRGV2Ijp7fX0sImN1c3RvbVJhbmdlIjpudWxsLCJzeW1ib2xzIjpbeyJzeW1ib2wiOiJGIiwic3ltYm9sT2JqZWN0Ijp7InN5bWJvbCI6IkYiLCJxdW90ZVR5cGUiOiJFUVVJVFkiLCJleGNoYW5nZVRpbWVab25lIjoiQW1lcmljYS9OZXdfWW9yayJ9LCJwZXJpb2RpY2l0eSI6MSwiaW50ZXJ2YWwiOiJ3ZWVrIiwidGltZVVuaXQiOm51bGwsInNldFNwYW4iOnsibXVsdGlwbGllciI6NSwiYmFzZSI6InllYXIiLCJwZXJpb2RpY2l0eSI6eyJwZXJpb2QiOjEsImludGVydmFsIjoid2VlayJ9fX1dfQ--

String in decoded form

{"interval":"week","periodicity":1,"timeUnit":null,"candleWidth":4.3486590038314175,"flipped":false,"volumeUnderlay":true,"adj":true,"crosshair":true,"chartType":"line","extended":false,"marketSessions":{},"aggregationType":"ohlc","chartScale":"linear","studies":{" vol undr ":{"type":"vol undr","inputs":{"id":" vol undr ","display":" vol undr "},"outputs":{"Up Volume":"#00b061","Down Volume":"#ff333a"},"panel":"chart","parameters":{"widthFactor":0.45,"chartName":"chart"}}},"panels":{"chart":{"percent":1,"display":"F","chartName":"chart","index":0,"yAxis":{"name":"chart","position":null},"yaxisLHS":[],"yaxisRHS":["chart"," vol undr "]}},"setSpan":{"multiplier":5,"base":"year","periodicity":{"period":1,"interval":"week"}},"lineWidth":2,"stripedBackground":true,"events":true,"color":"#0081f2","stripedBackgroud":true,"eventMap":{"corporate":{"divs":true,"splits":true},"sigDev":{}},"customRange":null,"symbols":[{"symbol":"F","symbolObject":{"symbol":"F","quoteType":"EQUITY","exchangeTimeZone":"America/New_York"},"periodicity":1,"interval":"week","timeUnit":null,"setSpan":{"multiplier":5,"base":"year","periodicity":{"period":1,"interval":"week"}}}]}

There is probably a lot of unnecessary information here, but the approach itself is clear.

Note. Because browsers can truncate URLs that are too long, it’s safer to use the standard Fragment URIs (line after sign #). As they say, everything new is a well-forgotten old. Cryptohosting Mega.co.nz implemented this method for transmission of the decryption key exactly ten years ago.

▍ Browser APIs tell the site owner about crashes on their page

Chrome implemented an interesting set of interfaces a couple of years ago.

Reporting API

which is still not known to all developers.

Through these APIs, the browser keeps track of users of your site and sends reports on crashes / errors from their side, simply by sending JSON to the specified URL.

True, currently in Chrome two incompatible API versionsso you need to figure out which version is better to use.

Thanks to these APIs, you can find non-standard errors on your pages. For example, frequent mobile browser crashes due to CSS animations. It turns out that standard CSS animations are too much for older smartphones – the browser crashes due to lack of RAM.

▍ CSS Trigonometric Functions

Speaking of CSS, a couple of months ago all major browsers added support for

trigonometric functions

.

Many people know that in the properties of CSS objects you can use mathematical expressions: from computing calc() to logic functions min(), max() And clamp().

And starting with Chrome 111, Firefox 108 and Safari 15.4, there is also support for trigonometric functions sin(), cos(), tan(), asin(), acos(), atan() And atan2(). All of them are described in the specifications. CSS Values ​​and Units Module Level 4.

For example, here is the code to rotate a point in a circle around the center point:

:root {
  --radius: 20vmin;
}

.dot {
  --angle: 30deg;
  translate: /* Translation on X-axis */
             calc(cos(var(--angle)) * var(--radius))

             /* Translation on Y-axis */
             calc(sin(var(--angle)) * var(--radius) * -1)
  ;
}

Demo

:

see also animated Möbius ring on sines and cosines.

PS About non-standard ways of using HTML / CSS / JS that surprised you, write in the comments or in a personal message.

Half a lemon of gifts from RUVDS. Answer questions and win prizes 🍋

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *