【问题标题】:When is the CKEDITOR script loaded and ready to use?CKEDITOR 脚本何时加载并准备好使用?
【发布时间】:2018-08-02 17:16:55
【问题描述】:

是否有更好的方法来确定何时加载 CKEDITOR 并且某些功能可用?我在下面包含了我们当前正在使用的代码,但它依赖于 setTimeouts 和计数器来经常检查 CKEDITOR 是否准备好。有时代码到达第一个 if 语句并且 CKEDITOR 可用(非空)但尚未加载事件处理,因此 CKEDITOR.on 不是函数。我本质上是在寻找一种依赖于事件处理的解决方案(也许是 CKEDITOR 准备就绪时触发的事件?)而不是 setTimeouts。

TL;DR:CKEDITOR.on 尚不能作为函数使用

只有某些页面需要 CKEDITOR,因此它会根据页面内容按需加载。

版本:使用 CKEDITOR 4.8

  Main.Script.getScript(javascript('external/ckeditor/ckeditor.js'), function() {
    var count = 0,
        init = function() {
          count++;
          if (CKEDITOR && CKEDITOR.on) {
            /*
              According to https://docs.ckeditor.com/ckeditor4/latest/api/CKEDITOR_editor.html#event-loaded,
              the "loaded" event is fired when editor components (configuration, languages, and plugins)
              are fully loaded and initialized.
             */
            CKEDITOR.on('loaded', function() {
              // Trigger _ckeditorReady event for custom event handling (CKEDITOR.on('instanceReady'), etc.)
              $(window).trigger('_ckeditorReady');
            });
          } else {
            if (count < 50) {
              $(script).ready(function() {
                setTimeout(init, 20);
              });
            }
          }
        };
    $(script).ready(function() {
      setTimeout(init, 20);
    });
  });

【问题讨论】:

  • 事件触发器将是理智的方法。我对 CKEditor 的了解还不够,无法说出这样的事件是否存在。但即使除此之外,似乎使用setInterval,也许与try / catch 块,将是比使用setTimeout 更清洁的方法。

标签: javascript jquery ckeditor


【解决方案1】:

instanceReady 事件,当编辑器加载并准备好交互时触发。 示例如何使用它:

CKEDITOR.replace( 'editor', {
  on: {
    'instanceReady': function( evt ) {
      var editor = evt.editor;
      console.log( 'Hello world' );
      console.log( JSON.stringify( CKEDITOR.tools.objectKeys( editor.plugins ) ) );
    }
  }
} );

实现相同事件的另一种方式:

var myeditor = CKEDITOR.replace( 'editor' );

myeditor.on( 'instanceReady', function( evt ) {
  var editor = evt.editor;
      console.log( 'Hello world' );
      console.log( JSON.stringify( CKEDITOR.tools.objectKeys( editor.plugins ) ) );
} );

来源:https://codepen.io/msamsel/pen/LQBLxw?editors=1111

【讨论】:

  • 感谢您抽出宝贵时间回复,但这并不能回答问题。如上所述,CKEDITOR.on 尚不能作为函数使用(脚本未完成加载),因此我无法使用它。我正在尝试找到一个解决方案,让我知道 CKEDITOR.on 何时可用。
  • @JuliaNething 它确实回答了这个问题,你只需要修复你的动态加载。
猜你喜欢
  • 1970-01-01
  • 2019-01-23
  • 2011-07-18
  • 2022-12-15
  • 1970-01-01
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多