2013-08-18 64 views
-1

使用ajax动态加载我的内容。我需要加载一个JavaScript文件后,我点击一个按钮:jQuery.getScript在DOM之前加载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

第1行的JavaScript文件,该文件通过上述功能和第3行称为加载的是真实加载的页面。

+0

你是否在加载dom之前单击按钮? – Musa

+0

是的,你如何在DOM准备好之前触发这个函数? – Jon

+0

当你点击'a#元素'时,它会转到另一个页面'http:// example.com/test'。 –

回答

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'); 
    }); 
    }); 
}); 
+0

该按钮通过ajax将“example.com/test”的div内容加载到主页“example.com”的maincontent div。然而,Firebug的网络面板在瀑布图中报告,在页面“http://example.com/test”加载之前,JavaScript正在被加载。 – Eric

+0

@Eric:看看我的jsbin http://jsbin.com/uJUBAru/1/edit ..这可能会给你一些线索 – Amith

+0

Thaks Amith,但问题仅仅是JavaScript在DOM之前加载(example.com /测试)。 请在我的问题中看到上面的截图 – Eric

0

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

其他建议?

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

});