Advanced Custom Fields

Automatically initialize WYSIWYG fields using IntersectionObserver
Admin pages with a lot of WYSIWYG fields can be significantly slow to load. That's why there is the option "Delay Initialization", that waits for the editor to be initialized as soon as the user clicks it. The related JS is from the days before IntersectionObserver was born – but it could now definitely be improved so that TinyMCE will be initialized as soon as the field enters the viewport. Here's a little function I wrote that does exactly that: /** * Attaches an intersection observer to delayed WYSIWYG fields * to enable them automatically if scrolled into view * * Uses the `ready_field` and field.addAction('load') actions * @see https://www.advancedcustomfields.com/resources/javascript-api/#actions-ready_field * @see https://www.advancedcustomfields.com/resources/javascript-api/#actions-load_field */ handleACFWysiwygField = () => { /** * Is the field delayed? */ const isDelayed = (field) => { return field.$control().hasClass("delay"); }; /** * This function will be injected into the ACF field object. * So `this` will be the field */ function observe() { if (!isDelayed(this)) { return; } const field = this; const $wrap = field.$control(); const observer = new IntersectionObserver( (entries) => { if (entries[0].isIntersecting) { $wrap.trigger("mousedown"); observer.disconnect(); } }, { rootMargin: "300px 0px", } ); observer.observe($wrap[0]); } /** * As soon as the field is ready, prepare it * for observation */ function onReady(field) { if (!isDelayed(field)) { return; } field .$control() .find(".acf-editor-toolbar") .text("Initializing Editor ..."); field.observe = observe.bind(field); field.addAction("load", field.observe); } acf?.addAction("ready_field/type=wysiwyg", onReady); }; The function does the following things: wait for any wysiwyg field to be ready if the field is delayed wait for the field to be fully loaded ( field.addAction('load') ) patches the field with an "observe" function, that observes it and initializes the editor as soon as the field becomes within 400px of the viewport As this all can already be done using the JS API, I thought it would be worth sharing it publicly. But if the ACF support is reading this, maybe they'd consider adding the functionality to the core?
0
Load More