JavaScript - 如何确保加载jQuery? [英] JavaScript - How do I make sure a jQuery is loaded?

查看:92
本文介绍了JavaScript - 如何确保加载jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页。加载此网页时,我想执行一些JavaScript。这个JavaScript使用JQuery。但是,似乎在加载页面时,jQuery库尚未完全加载。因此,我的JavaScript无法正常执行。

I have a web page. When this web page is loaded, I want to execute some JavaScript. This JavaScript uses JQuery. However, it appears that when the page is loaded, the jQuery library has not been fully loaded. Because of this, my JavaScript does not execute properly.

在执行JavaScript之前,确保加载jQuery库有哪些最佳实践?

What are some best practices for ensuring that your jQuery library is loaded before executing your JavaScript?

推荐答案

jQuery库应该包含在< head> 中页面的一部分:

The jQuery library should be included in the <head> part of your page:

<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>

您自己的代码应该在此之后。 JavaScript是线性和同步加载的,因此只要您按顺序包含脚本,就不必担心它。

Your own code should come after this. JavaScript is loaded linearly and synchronously, so you don't have to worry about it as long as you include the scripts in order.

在DOM中执行代码已完成加载(因为在发生这种情况之前你不能真正使用大量的jQuery库),请执行以下操作:

To make your code execute when the DOM has finished loading (because you can't really use much of the jQuery library until this happens), do this:

$(function () {
    // Do stuff to the DOM
    $('body').append('<p>Hello World!</p>');
});

如果你正在混合JavaScript框架并且它们互相干扰,你可能需要使用jQuery像这样:

If you're mixing JavaScript frameworks and they are interfering with each other, you may need to use jQuery like this:

jQuery(function ($) { // First argument is the jQuery object
    // Do stuff to the DOM
    $('body').append('<p>Hello World!</p>');
});

这篇关于JavaScript - 如何确保加载jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆