如何使用JavaScript添加jQuery? [英] How Do I Add jQuery To Head With JavaScript?

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

问题描述

我试图有条件地将jQuery包含在HTML页面中。如果它还不存在,只需要添加它。

I am trying to include jQuery to an HTML page conditionally. It only needs to be added if it doesn't exist yet.

我在我的body标签顶部附近使用以下代码来注入包含头部的jQuery库。

I am using the following code near the top of my body tag to inject a script tag that includes the jQuery library in the head.

<script type="text/javascript">

    if (typeof jQuery === 'undefined') {
        alert('now adding jquery');
        var head = document.getElementsByTagName("head")[0];
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js';
        head.appendChild(script);
        if (typeof jQuery === 'undefined') {
            alert('jquery still not present :(');
        }
    } else {
        alert('jquery already present');
    }
</script>

当我执行它时,我得到的信息是,添加后jQuery仍然不存在。脚本标记确实正确显示在已加载页面的源代码中。

When I execute it, I get the message that jQuery is still not present after adding it. The script tag does correctly show up in the loaded page's source.

尝试在我的页面中进一步使用jQuery,确认jQuery确实无效。正如预期的那样,Chrome的JavaScript控制台说$ not defined。

Trying to make use of jQuery a little further down below in my page, confirms that jQuery is indeed not working. As expected, Chrome's JavaScript console says '$ not defined'.

如何让它工作?

推荐答案

脚本异步加载。这意味着它的内容不是直接的附加元素后可用。

A script loads asynchronously. This means its contents are not directly available after appending the element.

使用 onload 代替:

script = document.createElement('script');

script.onload = function() {
    // jQuery is available now
};

script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js';

head.appendChild(script);

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

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