RequireJS实例

来源:互联网 发布:淘宝客如意投佣金比例 编辑:程序博客网 时间:2024/06/03 17:22

一、使用data-main加载主文件

目录结构


引用代码:

<script src="../scripts/require.js" data-main="../myjs/app.js"></script>

app.js代码:

console.info('app.js开始执行');console.info(require);
执行结果:


二、使用初始化配置和指定id加载js实例

<script src='../scripts/require.js'></script><script>//初始化配置require.config({baseUrl:'../myjs',paths:{jquery:'../scripts/jquery'}});//动态异步加载jsrequire(['jquery'],function($){$(function(){$(document.body).css({background:'#efefef'});});});</script>

加载顺序如下:


三、使用RequireJS构建模块实例

创建模块color.js定义颜色

//定义全局颜色define('color', function() {    return {    color:'red',    bgColor:'#efefef'    };});

创建style.js定义设置样式

//使用RequireJS定义模块,指定依赖define('style',['color','jquery'],function(color,$){    return {    init:function(){    $(document.body).css({    color:color.color,    background:color.bgColor    });    }    };});

创建require3.html 显示Demo

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script src='../scripts/require.js'></script><script >//全局配置require.config({baseUrl:'../myjs',paths:{jquery:'../scripts/jquery' //注意沒有文件后綴}});//加载style.js 配置页面样式require(['style'],function(style){//调用初始化style.init();});</script></head><body><h1>App首页</h1></body></html>


更多:Require.Js简介

更多实例:http://www.cnblogs.com/yexiaochai/p/3214926.html

0 0
原创粉丝点击