我的第一个requirejs例子,简单的demo

看介绍是很简单的,但是我做这个简单的demo,过程还是很曲折的。引进jquery,老是没引到,后来加上shim好了,再后来,去掉shim也是好的,我崩溃了。。。
二话不说上代码,给初学者看看。因为我在网上没找到一个完整的代码。要是有一个简单的demo就好了。我是看文档一步一步来的。

1、目录结构,

WebRoot
           js
                 config.js
                 require.js
                 jquery-3.0.0.min.js
                 a.js
           MyHtml.html               

2.文件,
MyHtml.html

<!DOCTYPE html>
<html>
<head>
<title>jQuery+RequireJS Sample Page</title>
</head>
<body>
    <h1>jQuery+RequireJS Test Page</h1>
    <p>Tests loading of jquery plugins with require.</p>
    <script src="js/require.js" data-main="js/a.js"></script>
</body>
</html>

a.js


require(['config'],function(config){
    require(['jquery'], function($) {
        debugger;
        alert($("body").css("background"));
    }); 
});

config.js

require.config({
    baseUrl: 'js',
    paths: {
        // the left side is the module ID,
        // the right side is the path to
        // the jQuery file, relative to baseUrl.
        // Also, the path should NOT include
        // the '.js' file extension. This example
        // is using jQuery 1.9.0 located at
        // js/lib/jquery-1.9.0.js, relative to
        // the HTML page.
        'jquery': 'jquery-3.0.0.min'
    }/*,
    shim: {
        'jquery': {
            exports: '$'
        }
    }*/
});

简单说一下,
html 里面的 data-main=”js/a.js 指的是入口文件,就是require第一个要引进的文件。

a.js 先引进一些配置文件,然后再引进 jquery。当初不加shim是访问不了jquery的,后面什么也没改就好了,我也搞不懂,而且我确定不是缓存问题。
shim 指的是 加载一些不是 define 定义的js,如

test.js

define(function(){
return {}
);
或者
define([‘jquery’],function($){
return {}
);

然后可以这样使用
require([‘test’],function(){
//do something
);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值