I would like to make a tool to improve the efficiency of lazy loading of images
In the text area
Enter the html code and click the button in the text area below
I want to build a program that duplicates the tag after the tag with the tag enclosed in

Applicable source code



  • Answer # 1

    String manipulation may be done using regular expressions.

    But here are DOMParser. It may not be as entered in the text area, but it can be processed by node operations.

    const parser = new DOMParser ();
        const doc = parser.parseFromString (val, 'text/html');
        const template = doc.createElement ('noscript');
        for (let i = doc.images.length;i--;) {
          let img = doc.images [i];
          let noscript = template.cloneNode (true);
          noscript.appendChild (img.cloneNode (false));
          img.parentElement.insertBefore (noscript, img.nextSibling);
          if (img.hasAttribute ('src')) {
            img.classList.add ('lazy');
            img.setAttribute ('data-original', img.getAttribute ('src'));
            img.removeAttribute ('src');
        console.log (doc.body.innerHTML);