jQuery.getScript在DOM之前加载javascript文件

时间:2013-08-18 18:17:16

标签: javascript ajax

使用ajax动态加载我的内容。点击按钮后我需要加载一个javascript文件:

<a id="element" href="http://example.com/test">button</a>

但是下面的脚本在加载DOM之前加载了javascript文件。 我该如何解决这个问题?

$("#element").click(function () {
  jQuery.getScript("example.com/jsfile.js?ver=0.9");  
}); 

firebug的截图:http://img607.imageshack.us/img607/1630/4mu7.png

第一行是通过上述函数调用的加载的javascript文件,第三行是正在加载的页面。

3 个答案:

答案 0 :(得分:0)

使用文档的readyState属性:

$("#element").click(function () {
    if(document.readyState === "complete")
        jQuery.getScript("example.com/jsfile.js?ver=0.9");
});

https://developer.mozilla.org/en-US/docs/Web/API/document.readyState

答案 1 :(得分:0)

工作JSBin - http://jsbin.com/uJUBAru/1/edit

Jquery方法使用document.ready()

$(document).ready(function(){
  $("#element").click(function () {
    $.getScript("example.com/jsfile.js?ver=0.9").done(function(script, textStatus) {
        console.log( textStatus );
    })
    .fail(function(jqxhr, settings, exception) {
        console.log( 'error' );
    });
  });
});

答案 2 :(得分:0)

我为该功能设置了超时。现在页面加载并在5秒后加载javascript。 虽然这是一个解决方案,但它不是很安全。

还有其他建议吗?

    $("#element").click(function ()
{setTimeout(function(){
    jQuery.getScript("example.com/jsfile.js?ver=0.9");
}, 5000);

});
相关问题