简体   繁体   中英

Solving CodeMirror library conflict error "Uncaught TypeError: CodeMirror is not a function" in WordPress

I maintain a plugin that makes use of the CodeMirror library in the admin dashboard. Some users complain of an "Uncaught TypeError: CodeMirror is not a function" which arises due to a conflict in CodeMirror versions. My plugin uses CodeMirror 2 (v5.x) which I instantiate using a custom script file after loading the library,

(function($){
  $(document).ready(function(){
    var options = {};
    var cmEditor = CodeMirror($('#cmeditor').get(0), options); //error thrown here.
    ...
  }
})(jQuery)

However, the older Codemirror 1 required a new object to be instantiated, var cmEditor = new CodeMirror(); , and this is where the conflict arises. If other plugins make sure of CodeMirror 1 and do not target admin pages properly (a common issue with poorly coded plugins) then my plugin attempts to instantiate an editor using the older library version that is loaded last.

So how does one ensure that the script uses the correct library?

After some search on a general solution for javascript library conflict management, I came across this blog post on how to load and use different versions of jQuery in WordPress and this answer on the StackOverflow which uses the anonymous function construct to pass an object instantiated right after the required library is loaded. So I managed to solve my problem by using the wp_add_inline_script() function in WordPress.

wp_enqueue_script('codemirror-js', 'uri_path_to_js_folder/codemirror.js', null, '5.32');
wp_add_inline_script( 'codemirror-js', 'var cme_5_32 = CodeMirror(document.getelementById("cmeditor"),{});'

this will ensure that the object cme_5_32 is instantiated right after the CodeMirror library v5.32 is loaded by the browser and hence is using the correct library.

I then parse this object as an attribute to my script's anonymous function,

(function($, cme){
  $(document).ready(function(){
    ...
  }
})(jQuery, cme_5_32)

and now no more error!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM