[JS] 使用RequireJS引用UMeditor

UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码.

而UMeditor则是UEditor删减版.

本文将通过RequireJS的方式来加载UMeditor.

效果图:

普通方式:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="Scripts/umeditor/themes/default/css/umeditor.css" rel="stylesheet" />
</head>
<body>
    <script type="text/plain" id="myEditor" style="500px;height:240px;">
        <p>Hello World</p>
    </script>
    <script src="Scripts/umeditor/third-party/jquery.min.js"></script>
    <script src="Scripts/umeditor/umeditor.config.js"></script>
    <script src="Scripts/umeditor/umeditor.min.js"></script>
    <script src="Scripts/umeditor/lang/zh-cn/zh-cn.js"></script>
    <script>
        var um = UM.getEditor('myEditor');
    </script>
</body>
</html>

RequireJS:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="scripts/require.js" data-main="scripts/main" defer async="true"></script>
</head>
<body>
    <script type="text/plain" id="myEditor" style="500px;height:240px;">
        <p>Hello World</p>
    </script>
</body>
</html>

来看看我们的main.js

require.config({
    baseUrl: 'scripts/umeditor/',
    paths: {
        'jquery': 'third-party/jquery.min',
        'um.zh': 'lang/zh-cn/zh-cn',
        'um': 'umeditor'
    },
    shim: {
        um: ['umeditor.config', 'jquery'],
        'um.zh': ['um']
    }
});

require(['../css!themes/default/css/umeditor.css', 'um.zh'], function () {
    var um = UM.getEditor('myEditor');
});

从html代码来看RequireJS简洁的多.

再来比较一下加载速度吧

普通:

RequireJS:

明显Require的DOM加载速度非常快.

UMeditor一些踩坑点:

  • 在config.js中需要配置HOME_URL,用来解决依赖js路径问题.

  • 在config.js中需要根据项目配置上传地址

  • 在UMeditor Doc中介绍editor.setContent()为写入内容.而这段代码一定需要放到ready函数中
var ue = UE.getContent();
//对编辑器的操作最好在编辑器ready之后再做
ue.ready(function() {
    //设置编辑器的内容
    ue.setContent('hello');
    //获取html内容,返回: <p>hello</p>
    var html = ue.getContent();
    //获取纯文本内容,返回: hello
    var txt = ue.getContentTxt();
});
  • 在上传图片的时候,需要返回特定的json格式.但返回的Content-Type不可以为application/json.

本例中,同时使用了RequireJS.css插件实现css的加载.

为方便大家,同时在Nuget上上传了Nuget包.

Install-Package umeditor

原文地址:https://www.cnblogs.com/neverc/p/5674094.html