Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
getScript在DOM之前加载javascript文件_Javascript_Ajax - Fatal编程技术网

getScript在DOM之前加载javascript文件

getScript在DOM之前加载javascript文件,javascript,ajax,Javascript,Ajax,使用ajax动态加载我的内容。单击按钮后,我需要加载一个javascript文件: <a id="element" href="http://example.com/test">button</a> 萤火虫截图: 第一行是通过上述函数调用的已加载javascript文件,第三行是正在加载的页面。使用文档的readyState属性: $("#element").click(function () { if(document.readyState === "comp

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

<a id="element" href="http://example.com/test">button</a>
萤火虫截图:


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

使用文档的
readyState
属性:

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

工作
JSBin
-

Jquery方法使用document.ready()


我已经为函数设置了一个超时。现在加载页面,5秒后加载javascript。 虽然这是一种解决方案,但并不十分安全

还有其他建议吗

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

});

是否在加载dom之前单击按钮?是的,如何在dom准备就绪之前触发此函数?当单击
a#元素时,它将转到另一页
http://example.com/test
。否在加载dom后单击按钮。@khan,是的,它将毫无问题地转到该页面。该按钮通过ajax将“example.com/test”的div内容加载到主页“example.com”的maincontent div。但是Firebug的网络面板在瀑布图中报告javascript在加载页面“”之前加载。@Eric:看看我的jsbin..这可能会给你一些错误,但问题只是javascript在DOM之前加载(example.com/test)。请看我的问题上面的截图
$(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' );
    });
  });
});
    $("#element").click(function ()
{setTimeout(function(){
    jQuery.getScript("example.com/jsfile.js?ver=0.9");
}, 5000);

});