I have the TinyMCE plugin on my site. When adding images in the textarea of the TinyMCE plugin, I want these images to have lazy loading incorporated. My site's thumbnails has a specific type of lazy loading where the src image is a gray background. Depending on the size of the user's screen, the type of image is loaded. Mobile images have the data attribute of data-mobile-src and the desktop images have the data attribute of data-large-src.
How do I make it so that once the textarea is uploaded my database's table, the images can be lazy loaded?
For anyone looking in the future, you can use the extended_valid_elements.
This property is used to allow valid attributes, and you can specify a default value for them. So basically, this line adds 'loading=lazy' automatically.
extended_valid_elements : 'img[class|src|alt|title|width|loading=lazy]',
I understand some of you guys want to use data-src like techniques to support older browsers, I couldn't find a decent way to do using any of the configs TinyMCE provides. As solution, I think this works just fine
let htmlString be the content string received from tinymce and
const doc = new DOMParser().parseFromString(htmlString, "text/html");
doc.body.querySelectorAll('img').forEach(img => {
img.setAttribute('data-src', img.src),
img.removeAttribute('src')
})
console.log(doc.body.innerHTML) // your html to be sent to the server
You can even use this technique to change images into picture elements and srcset them. This technique can be implemented on the server side too, using the JSDom library.