-1

使用 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");  
}); 

萤火虫截图:http: //img607.imageshack.us/img607/1630/4mu7.png

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

4

3 回答 3

0

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

还有其他建议吗?

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

});
于 2013-08-19T09:28:19.777 回答
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

于 2013-08-18T18:24:22.457 回答
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' );
    });
  });
});
于 2013-08-18T18:26:17.457 回答