1.require.js loading
<script src="js/require.js" defer async="true" data-main="js/main"></script>
Note: anync="true" loads js asynchronously, defer is the asynchronous loading method supported by ie.
2. Writing the main module
/** * Created by zhanghaov on 2018/3/21. */ require.config({ paths:{ "jquery":"jquery-1.8.3", "math":"math" } // baseUrl: "js/lib" configurable default path }); require(['jquery','math'],function($,math){ var result = math.add(5,10); console.log($(".box").html()); console.log(result); $.toSay({ name:'abc', age:213 }); });
3. Custom modules (following AMD specifications)
/** * Created by zhanghaov on 2018/3/21. */ //According to AMD regulations, customize the module define() function define(['jquery'],function($){ var add = function(x,y){ return x + y; }; var req = function(){ $.ajax({ url:'www.baidu.com', type:'POST', data:{ name:'lee', age:'12' }, success:function(data){ } }); } $.extend({ toSay:function(options){ var defaults = { name:'lee', age:14 } var settings = $.extend(true,defaults,options); for(var i in settings){ console.log(i + "==" +settings[i]); } } }); return { add:add, req:req }; });