在CDN不可用的情况下,如何加载本地jQuery文件
jQuery是一个轻量级的、”少写多做 “的JavaScript库。jQuery有助于尽可能简单地编写JavaScript。它能有效地将JavaScript中的几行代码转换为一行。它还简化了Ajax调用和DOM(文档对象模型)等任务。
jQuery库包含以下功能。
有很多方法可以在你的应用程序中使用jQuery,其中一种比其他的更容易。下面是一些你可以用来加载本地jquery文件的方法。
方法1:使用jQuery CDN(内容交付网络)。
例子:在这个例子中,我们将简单地在脚本标签中加入CDN行,如果你点击提交按钮,你将看到你的名字在浏览器中显示为警告。
<!DOCTYPE html>
<html>
<head>
<!--Script loaded from Google CDN service-->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<h2 style="color:green">GeeksforGeeks</h2>
<p>Using the CDN link for jQuery</p>
<input type="text" placeholder="Name...." id="name">
<button id="btn">Submit</button>
<script>
("#btn").click(function (event) {
// If you click the submit button
// you will see your name coming
// up as alert in the browser
event.preventDefault();
var name =("#name").val();
alert(name);
});
</script>
</body>
</html>
输出:
有CDN链接
现在我们将看到如何在上述CDN不可用的情况下加载本地jquery文件。
方法2:下载jQuery在本地使用。
从这里下载jQuery库。有两个版本的jQuery,你可以下载。
- 生产版本。这是为你的实时网站准备的,因为它已经被最小化和压缩了。
- 开发版本。这是用于测试和开发(未压缩的可读代码)。
从这个页面下载jquery库链接
- 下载的文件将是一个单一的JavaScript文件,你可以按图索骥。在保存在你当前的文件夹中时,重命名它并在你的标题部分包括相同的名称,同时包括库文件。
例子:在这个例子中,我们将下载库文件“ jquery.min.js”,而不是使用CDN,如果你点击提交按钮,你将看到你的名字在浏览器中出现提示。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<!--In case cdn fails, local will load up for sure-->
<script>
window.jQuery || document.write(
'<script src="jquery.min.js">\x3C/script>'
)
</script>
<!--'\x3C' has been used so that the script
does not end prematurely. The above
condition checks whether local has
loaded if not then it loads up the
local -->
</head>
<body>
<h2 style="color:green">GeeksforGeeks</h2>
<p>
This works with library downloaded
in the current folder
</p>
<input type="text" placeholder="Name...." id="name">
<button id="btn">Submit</button>
<script>
("#btn").click(function (event) {
// If you click the submit button you
// will see your name coming up as
// alert in the browser
event.preventDefault();
var name =("#name").val();
alert(name);
});
</script>
</body>
</html>
输出:
用一个下载的jquery库
注意:脚本标签的源码(src)中的路径需要被正确配置。它应该被设置为正确的路径,以便jQuery能够完美地工作。
你也可以使用npm(node package installer)将jQuery安装为一个node包。
npm install jquery
你也可以用yarn CLI安装它,命令如下。
yarn add jquery