AMD

  • require.js requirejs.org/
  • 全局define函数
  • 全局require函数
  • 依赖JS会自动、异步加载
  1. //util.js
  2. define(function () {
  3. return{
  4. getFormatDate: function (date,type) {
  5. if (type === 1) {
  6. return '2017-06-15'
  7. }
  8. if (type === 2) {
  9. return '2017年6月15日'
  10. }
  11. }
  12. }
  13. });
  14. //a-util.js
  15. define(['./util.js'],function (util) {
  16. return{
  17. aGetFormatDate: function (date) {
  18. return util.getFormatDate(date,2);
  19. }
  20. }
  21. });
  22. // a.js
  23. define('[./a-util.js]',function (aUtil) {
  24. return{
  25. printDate:function (date) {
  26. console.log(aUtil.aGetFormatDate);
  27. }
  28. }
  29. });
  30. //main.js
  31. require('[./a.js]',function (a) {
  32. var date = new Date();
  33. a.printDate(date);
  34. });
  • 使用
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Document</title>
  6. </head>
  7. <body>
  8. <p>AMD test</p>
  9. <script src="/require.min.js" data-main="./main.js"></script>
  10. </body>
  11. </html>