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文件;您将收到以下输出:

RequireJS教程:从CDN加载jQuery

作者:terry,如若转载,请注明出处:https://www.web176.com/requirejs/1994.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年2月9日 下午5:21
下一篇 2021年2月9日 下午5:25

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注


Fatal error: Uncaught JSMin_UnterminatedStringException: JSMin: Unterminated String at byte 554: ", in /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php:214 Stack trace: #0 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php(152): JSMin->action() #1 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php(86): JSMin->min() #2 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/ao-minify-html.php(257): JSMin::minify() #3 [internal function]: AO_Minify_HTML->_removeScriptCB() #4 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/ao-minify-html.php(108): preg_replace_callback() #5 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/ao-minify-html.php(47): AO_Minify_HTML->process() #6 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/autoptimizeHTML.php(105): AO_Minify_HTML::minify() #7 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/aut in /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php on line 214