Categories: RequireJS教程

RequireJS教程:从CDN加载jQuery

jQuery使用CDN(内容交付网络)通过调用define()函数来定义jQuery插件的依赖项。

加载jQuery

define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) {
   $(function() {
      //code here
   });
});

以下示例使用CDN定义jQuery插件的依赖项。创建一个名称为index.html的html文件,并将以下代码放入其中:

<!DOCTYPE html>
<html>
   <head>
      <title>Load jQuery from a CDN</title>
      <script data-main = "app" src = "lib/require.js"></script>
   </head>
   
   <body>
      <h2>Load jQuery from a CDN</h2>
      <p>Welcome to Tutorialspoint!!!</p>
   </body>
</html>

创建一个名为app.jsjs文件,并在其中添加以下代码:

// you can configure loading modules from the lib directory
requirejs.config ({
   "baseUrl": "lib",
   
   "paths": {
      "app": "../app",
   
      //loading jquery from CDN
      "jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min"
   }
});

//to start the application, load the main module from app folder
requirejs(["app/main"]);

创建一个名为app的文件夹,并从该文件夹加载main.js模块:

define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) {
   
   //loading the jquery.load_js1.js and jquery.load_js2.js plugins 
   $(function() {
      $('body').load_js1().load_js2();
   });
});

再创建一个名为lib的文件夹,以存储require.js文件和其他js文件,如下所示:

lib / jquery.load_js1.js

define(["jquery"], function($) {
   
   $.fn.load_js1 = function() {
      return this.append('<p>Loading from first js file!</p>');
   };
});

lib / jquery.load_js2.js

define(["jquery"], function($) {
   
   $.fn.load_js2 = function() {
      return this.append('<p>Loading from second js file!</p>');
   };
});

输出

在浏览器中打开HTML文件;您将收到以下输出:

terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

6 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

2 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

3 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

4 周 ago