且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery - 在脚本加载并执行后触发AJAX回调?

更新时间:2023-11-21 18:11:28

你应该查看jquerys

Your should look in to jquerys when

允许您在执行多个异步(ajax)方法后执行代码。

Will allow you to execute code after multiple async (ajax) methods are done executing.

从jquery文档:


描述:提供一种基于一个
或更多对象执行回调函数的方法,通常是Deferred对象表示异步
事件。

Description: Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

https://api.jquery.com/jquery.when/

至于要执行的脚本在运行代码之前,jquery有一个解决方案; getScripts

$.getScript("jquery.cookie.js")
    .done(function() {
        jQuery.cookie("cookie_name", "value", { expires: 7 });
});

加载多个脚本并在运行代码之前执行它们,方法是结合 getScript 何时

Load multiple scripts and execute them before running your code by combining getScript and when

$.when(
    $.getScript( "/script1.js" ),
    $.getScript( "/script2.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );
    })
).done(function(){

    // your code

});

另一种方法:

var scripts = ['script1.js','script2.js','script3.js'];
$.getScript(scripts, function(data, textStatus) {
    //do something after all scripts have loaded
});

参考: http://www.sitepoint.com/getscript-mutiple-scripts/