📜 ⬆️ ⬇️

Mobify.js - changing the DOM before starting to load resources

image

Mobyfy.js is an open library designed primarily to facilitate the creation of responsive (responsible) sites. The main feature is the so-called “Capturing API” - which allows modifying the DOM directly BEFORE the browser starts loading resources (scripts, images, etc.)

Here is an example of working with responsive images:

<picture> <source src="/examples/assets/images/small.jpg"> <source src="/examples/assets/images/medium.jpg" media="(min-width: 450px)"> <source src="/examples/assets/images/large.jpg" media="(min-width: 800px)"> <source src="/examples/assets/images/extralarge.jpg" media="(min-width: 1000px)"> <img src="/examples/assets/images/small.jpg"> </picture> 

The file “small.jpg” will not be loaded on the client with a large screen, instead it will load what will meet the media criteria (you can check it in the web inspector on the “network” tab).
')
Sample code that replaces all the images on the page:
Expand Code
 <script id="main-executable" class="mobify"> var main = function () { var capturing = window.Mobify && window.Mobify.capturing || false; if (capturing) { // Grab reference to a newly created document Mobify.Capture.init(function(capture){ var capturedDoc = capture.capturedDoc; var grumpyUrl = "/mobifyjs/examples/assets/images/grumpycat.jpg" var imgs = capturedDoc.getElementsByTagName("img"); for(var i = 0; i < imgs.length; i++) { var img = imgs[i]; var ogImage = img.getAttribute("x-src"); img.setAttribute("x-src", grumpyUrl); img.setAttribute("old-src", ogImage); } // Render source DOM to document capture.renderCapturedDoc(); }); } }; main(); </script> 

The principle of operation is quite interesting: on the page, the script that temporarily wraps the contents of the BODY in the PLAINTEXT tag is inserted at the beginning of the HEAD tag - this prevents the download of resources. Next, we execute our code, manipulate the DOM, and at the end of the BODY is restored and resources are loaded.

Browser Support:

The official site , an interesting discussion on the site of the Mozilla - in the comments there is an explanation of the technology.

Source: https://habr.com/ru/post/193972/


All Articles