首页 > 解决方案 > 如何仅在需要它的页面上加载 CKEditor?

问题描述

我正在使用CKEditor gem。它仅用于管理页面。我只想在需要它的页面上使用它。我注释掉了 Sprocket 指令application.js

// only load on required pages // require ckeditor/init

我将它添加到顶部的表单页面

<%= javascript_include_tag 'ckeditor/init' %>

然而,它有时只起作用。如果我在没有它的情况下重新加载页面,并导航到它的页面,那么它会加载脚本,但无法装饰文本框。没有控制台错误。

如果我用它重新加载页面,那么它会成功并装饰文本框。

如果我重新加载没有它的页面,导航到它的页面,导航到没有它的页面,然后导航回它的页面,然后它会成功并装饰文本框,但会发出控制台警告

[CKEDITOR] 错误代码:editor-destroy-iframe。
[CKEDITOR] 有关此错误的更多信息,请访问http://docs.ckeditor.com/#!/guide/dev_errors-section-editor-destroy-iframe

该链接说

描述:无法正确销毁编辑器,因为在销毁编辑器之前已将其卸载。确保在将编辑器与 DOM 分离之前将其销毁。

我很确定这是一个 Turbolinks 问题。我会添加一个$(document).on 'turbolinks:load'事件处理程序,但我不知道要使用什么 DOM id 或如何“初始化”或“销毁”CKEditor。

导轨 5.2.2


我试过了,修复了类和事件名称https://github.com/galetahub/ckeditor#turbolink-integration

ready = ->
  $('.ckeditor_class').each ->
    CKEDITOR.replace $(this).attr('id')
    console.log("ck'd "+$(this).attr('id'))

$(document).ready(ready)
$(document).on('turbolinks:load', ready)

但它给出了一个控制台错误

未捕获的 ReferenceError:CKEDITOR 未定义


我试过这个

$(document).on 'turbolinks:load', ->
  setTimeout ->
    if CKEDITOR?
      $('.ckeditor_class').each ->
        CKEDITOR.replace $(this).attr('id')
  , 1000

当从没有它的页面导航到有它的页面时它可以工作但是当重新加载一个有它的页面时,会给出控制台错误

未捕获编辑器实例“question_prompt”已附加到提供的元素。

没有办法知道它是否已经初始化。例如:CKEDITOR.instances没有length财产。

标签: javascriptruby-on-railsckeditorturbolinks

解决方案


也许是这样的

check_ckeditor_loaded = function($el) {
  if (typeof CKEDITOR !== "undefined" && CKEDITOR !== null) {
    if ($.isEmptyObject(CKEDITOR.instances)) {
      CKEDITOR.replace($el.attr('id'));
    }
    # make other magic 
  } else {
    setTimeout((function() {
      return check_ckeditor_loaded($el);
    }), 100);
  }
};


$(document).on 'turbolinks:load', ->
  $('.ckeditor_class').each ->
    $el = $(this)
    check_ckeditor_loaded($el);

推荐阅读