动态加载后无法使用jquery

时间:2015-01-09 19:34:14

标签: javascript jquery html

我将data.js加载到我的a.html页面。

在我的data.js中,我正在检查a.html是否有jquery并且如果没有则加载它。加载jquery后我正在进行ajax调用,但我正在

$ is not defined

异常。

这是我的data.js

if(typeof jQuery=='undefined') {
            var headTag = document.getElementsByTagName("head")[0];
            var jqTag = document.createElement('script');
            jqTag.type = 'text/javascript';
            jqTag.src = 'http://localhost:8001/jquery-min.js';
            headTag.appendChild(jqTag);
        }

        var url = 'http://127.0.0.1:5000';

        $.ajax({
            url: url,
            success: function(data) {
               $("#" + containerId).html(data);
            },
            error: function(e) {

               console.log(e.message);
            }
        });

从开发者控制台,我可以看到加载了jquery。我可以在Resources和head标签中看到它。

2 个答案:

答案 0 :(得分:2)

当您进行AJAX调用时,jQuery(以及$因此)尚未加载,因为您只是将脚本标记添加到DOM中。之后开始下载。相反,您应该绑定脚本标记的onload事件,并在加载后执行操作。

实施例

jqTag.onload = function() {
    var url = 'http://127.0.0.1:5000';

    $.ajax({
        url: url,
        success: function(data) {
           $("#" + containerId).html(data);
        },
        error: function(e) {

           console.log(e.message);
        }
    });
}
jqTag.src = 'http://localhost:8001/jquery-min.js';

答案 1 :(得分:-3)

更改此行:

if(typeof jQuery=='undefined')

if(typeof jQuery== undefined ) {