是否有事件或其他方法告诉我预览已加载?

时间:2018-07-03 作者:Milli

我正在为WordPress定制器开发一个插件,需要在预览器加载后调用一个函数。是否有事件或其他方法告诉我已加载预览?

如果已尝试:

jQuery(window).load (function() { // Customizer loaded...
   wp.customize.previewer.bind( \'refresh\', function() { // doesn\'t seem to work ?!
      alert (\'Previewer has loaded\'); 
   }
}
我也试过了wp.customizer.bind(\'refresh\', function (){

加载预览时是否没有触发任何事件?刷新预览器时,将触发刷新事件。

有什么想法吗?

2 个回复
最合适的回答,由SO网友:Weston Ruter 整理而成

是的,这是检测预览何时加载的方法:

wp.customize.bind( \'ready\', function() {
  wp.customize.previewer.bind( \'ready\', function( message ) {
     console.info( \'Preview is loaded\' );
  } );
} );
此JS代码应在customize_controls_enqueue_scripts 与的操作customize-controls 脚本作为其依赖项。

SO网友:Milli

我没有找到加载预览时的自定义程序API事件。以下是iframe上有加载事件的解决方案:

// Assures that the code gets runned once per load.
var code_has_run = false;

function preview_loader(){
    // When the customizer has loaded the iframe does not
    // exist yet. This checks if the iframe exists.

    if (jQuery(\'#customize-preview iframe\').length > 0){    

        // When iframe/preview has loaded.
        jQuery(\'#customize-preview iframe\').on(\'load\', function (){

            // Wait a little until old frame is removed.
            setTimeout(function (){
                if (code_has_run == false){
                    // Code to be run when preview has loaded and is ready.
                    alert(\'Preview loaded\');
                }
                code_has_run = true;

                // Wait until multiple load events are finished. 
                setTimeout(function(){
                    code_has_run = false;
                }, 1000);
            }, 1000);          
        });
    }
}

jQuery(window).load (function() { // Customizer loaded...

    //Call preview_loader if the preview loads under 500ms.
    preview_loader();

    setInterval(preview_loader, 500);  
}

结束