如何使用jQuery将TypeKit字体加载到CKEditor实例中

我正在尝试通过jQuery将TypeKit字体加载到CKEditor的实例中。 这是我的代码:

$('.ck-blog textarea').ckeditor(function () { CKEDITOR.scriptLoader.load( "http://use.typekit.com/zku8fnp.js", function (success) { Typekit.load(); alert(success); }, null, true); }, { resize_enabled: false, skin: 'kama', height: '500px', toolbarCanCollapse: false, toolbar_Full: toolbar, forcePasteAsPlainText: true, autoGrow_onStartup: true, templates_replaceContent: false, extraPlugins: 'autogrow,wordcount', removePlugins: 'resize', contentsCss: '/areas/admin/content/css/ckeditor-blog.css', templates_files: ['/areas/admin/scripts/ckeditor-templates.js'], autoParagraph: false }); 

在TypeKit应该加载后我得到了成功警报,但我没有看到字体加载。 知道我可能做错了什么吗?

这是我在通过互联网挖掘3小时后成功组装的:

 CKEDITOR.on( 'instanceReady', function(ev) { var $script = document.createElement('script'), $editor_instance = CKEDITOR.instances[ev.editor.name]; $script.src = '//use.typekit.com/MYKEY.js'; $script.onload = function() { try{$editor_instance.window.$.Typekit.load();}catch(e){} }; $editor_instance.document.getHead().$.appendChild($script); } ); 

这里的诀窍是使用来自iframe的CKEditor的“窗口”对象。

CKEDITOR.scriptLoader似乎用于将资源加载到父窗口, 而不是加载到iframe’d document 。 这会导致上面的代码执行并将Typekit字体重新应用于父窗口而不是iframe。

我的解决方案是在父窗口中设置document.domain ,动态创建元素,将它们附加到iframe document

1.您的Typekit具有域白名单。 除非您在父窗口中将document.domain指定为该白名单中的域,否则CKEditor不会设置标记的src属性以在此白名单中返回有效值。

 document.domain = "example.com"; 

我用类似的行创建了脚本

 script1 = document.newElement('script'); script1.src = "https://use.typekit.com/MYKEY.js"; script2 = document.newElement('script'); script2.text = "try{Typekit.load();}catch(e){}"; 

3.然后我将这些附加到dom (我在我的项目中使用jQuery,这就是我如何定位元素)

 head = jQuery('textarea.editor').ckeditorGet().document.getHead().$; head.appendChild(script1); head.appendChild(script2); 

现在应用了Typekit字体。

修改后在CKEditor设置中使用

  editors.ckeditor(function(){ var head = this.document.getHead().$, script1 = document.newElement("script"), script2 = document.newElement("script"); script1.src = sprintf("https://use.typekit.com/%s.js", app_typekit_id); script2.text = "setTimeout(function(){ try{Typekit.load();}catch(e){} }, 0);"; head.appendChild(script1); head.appendChild(script2); }, { //... your custom config }); 

也许有比setTimeout(function(){ ... }, 0);更好的方法setTimeout(function(){ ... }, 0); (延迟0ms) ,但只留下try{Typekit.load();}catch(e){}并没有给script1足够的时间来追加并解释为浏览器开始阻塞。 还要注意,我上面使用的sprintf()来自一个库(不是本机JS)