jQuery - 在脚本加载并执行后触发AJAX回调? [英] jQuery - fire AJAX callback after script has been loaded AND executed?
问题描述
我遇到了一个需要AJAX加载一些脚本的问题,只有一旦脚本被加载和解析/执行,才应该触发回调函数。
I'm running into an issue where I need to AJAX load some scripts, and only once the scripts have been both loaded and parsed/executed, should the callback function should fire.
似乎ajax请求会在脚本下载后立即触发回调,但不一定会在执行脚本时触发。有没有办法做到这一点,而不是使用Timeouts等等?
It appears that ajax requests will fire the callback as soon as the script is downloaded, but not necessarily when it's been executed. Is there a way to do this other than mucking around with Timeouts and such?
$.ajax({
dataType: 'script',
cache: false,
async: false,
url: 'http://example.com/script1.js'
}).success(function () {
// I need this callback to fire only once the script has been executed
});
推荐答案
你应该查看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/
这篇关于jQuery - 在脚本加载并执行后触发AJAX回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!