RequireJS 按需加载js模块

1.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
    <input type="button" id="button1" value="Click">
    <input type="button" id="button2" value="Click">
    <script src="https://cdn.bootcss.com/require.js/2.3.5/require.js" data-main="js/index"></script>
</body>
</html>

2.上面html文件中data-main对应的index.js文件

require.config({
    baseUrl: 'js'
});

require(['myModule'], function (myModule){
    $('#button1').click(function () {
        alert('button1');
    });

    myModule.myFun();
});

3.上面index.js文件中对应myModue.js文件

define(function (){
    var myModule = {
        myFun: function () {
            $('#button2').click(function () {
                alert('button2');
            });
        }
    };

    return myModule;
});

4.目录结构



原文地址:https://www.cnblogs.com/xutongbao/p/9924985.html