📜  何时使用 Vanilla JavaScript 与 jQuery?

📅  最后修改于: 2021-11-25 03:31:37             🧑  作者: Mango

早些时候,这些网站曾经是静态的。然而,vanilla JavaScript 的引入彻底改变了网站过去的外观和函数。 Vanilla JS 帮助开发人员创建动态网站。然后是 jQuery,这是一个由世界各地的开发人员使用 Javascript 创建的工具库。

简而言之,jQuery 是一个轻量级且易于使用的 JavaScript 库,它有助于用几行代码创建复杂的功能。 jQuery 有助于 CSS 操作、发出 AJAX 请求、处理从服务器接收的 JSON 数据,还有助于向组件添加隐藏、显示等动画效果。最好的部分是 jQuery 是浏览器灵活的。这意味着 jQuery 兼容市场上的所有浏览器,因此开发人员不必担心用户可能使用的浏览器。

jQuery 简化了很多事情。使用 jQuery 实现一些东西比使用 vanilla JS 更容易。看看这个例子。在这里,我们必须在屏幕上显示一条弹出消息,一旦用户单击'click here for popup!"按钮’。

jQuery代码:



  

    
    
    

  

    
  
    

  

输出:

  • 点击按钮前:
  • 点击按钮后:

JavaScript 代码:



  

    
    

  

     
  
    

  

输出:

  • 点击按钮前:
  • 点击按钮后:

很容易看出,jQuery 编码比普通 JS 代码更短、更简化。让我们看一下另一个例子,以便更好地理解。

假设程序员想要选择所有类名 = 'hello'元素。
Javascript

document.getElementsByClassName("hello");  

jQuery

$('hello')

没有书面的规则手册告诉在何处使用 jQuery 以及在何处使用 JavaScript。据说 jQuery 在 DOM 操作方面比 Javascript 更好,但是,在监控两者的性能后,发现 vanilla JS 比 jQuery 更快。然而,对于新手程序员来说,使用 Javascript 编写复杂的功能可能会变得很困难。

jQuery 与 Javascript

JavaScript jQuery
A weakly typed dynamic programming language. A rich, lightweight, and easy to use JavaScript library.
A scripting language used for creating dynamic websites user friendly interfaces. JS framework used to handle AJAX requests, manipulate CSS, and create animations like as slide, hide etc.
All the coding has to be done from scratch. Might turn out to be difficult and time consuming for novice programmers. jQuery has several pre-written functions. Only the necessary modifications has to be made. Saves a lot of time.
Developers have to take care of multi browser compatibility. Browser related errors are more like to appear. jQuery works with all modern browsers. There is no such compatibility issue with any browser.
No additional plugins are required to run JS. Do not need to add any additional plugins as all browsers support JavaScript. jQuery library script link has to be included inside the head tag of the webpage.
Long line of code. May lead to spaghetti codes. Less coding is required to do the same work.
DOM can be accessed faster. It is best for complex operations where developers usually make mistakes and write poor lines of code.
Not easy to learn. Learning curve is steep. Comparatively easier to learn.

简而言之,jQuery 是使用 WordPress、Weebly 等 CMS 网站时更好的选择。由于它已经拥有庞大的插件库,它使开发更容易。然而,即使 jQuery 是由 Javascript 组成的,忽略 vanilla Javascript 也不是一个明智的决定。如果您想成为前端或全栈 Web 开发人员,那么学习 vanilla JS 是必要的。这是因为 Javascript 也有其他框架和库,如 Angular、React 和 Vue,它们比 jQuery 有很多优势。这就是为什么建议首先深入学习 vanilla JS,因为库和框架会来来去去,但它们的基础始终是 vanilla JS。这就是为什么在面试中,了解 Javascript 的候选人将比其他了解 jQuery 的候选人更具优势。

还必须知道,学习 vanilla JS 的人会发现切换到 jQuery 会更容易。但是,从 jQuery 切换到 Javascript 一开始似乎并不顺利。根据最近的一项调查,互联网上排名前 100 万的网站中约有 77% 使用 jQuery,首先学习 vanilla 语言始终是前进的最佳方式。