Javascript 为JS函数使用脚本_队列时的执行顺序
在我们的工作场所,我们在site.master页面中定义了一个脚本队列Javascript 为JS函数使用脚本_队列时的执行顺序,javascript,jquery,Javascript,Jquery,在我们的工作场所,我们在site.master页面中定义了一个脚本队列 <script> // append functions to this array that will be executed after js dependencies have loaded var script_queue = []; </script> //将函数追加到此数组,该数组将在加载js依赖项后执行 var脚本_队列=[]; 然后我们将javascript函数推
<script>
// append functions to this array that will be executed after js dependencies have loaded
var script_queue = [];
</script>
//将函数追加到此数组,该数组将在加载js依赖项后执行
var脚本_队列=[];
然后我们将javascript函数推送到这个脚本队列来执行它们。我遇到了一个问题,比如说我有两个函数
<script type="text/javascript">
// THIS IS FUNCTION 1
script_queue.push(function() {
// set the width of the thumbnail list to the sum of all the li widths
var thumbsWidth = 0;
$('#oneClipPlaylist li').each(func
…
}
</script>
script_queue.push(function() {
// THIS IS FUNCTION 2
var allInputs = $('fieldset.categories input');
var categoryInputs = $('fieldset.categories input').not('#categoryAll');
var categoryAllInput = $('#categoryAll');
allInputs.click(function() {
var checkbox = $(this);
//这是功能1
脚本_queue.push(函数(){
//将缩略图列表的宽度设置为所有li宽度的总和
var thumbsWidth=0;
$('oneClipPlaylist li')。每个(func
…
}
脚本_queue.push(函数(){
//这是功能2
var allInputs=$('fieldset.categories input');
var categoryInputs=$('fieldset.categories input')。而不是('categoryAll');
var categoryAllInput=$(“#categoryAll”);
所有输入。单击(函数(){
var复选框=$(此);
以下是队列的处理方式:
<script>
(function () {
for (var i in script_queue) {
script_queue[i]();
}
} ());
</script>
(函数(){
对于(脚本_队列中的变量i){
脚本_队列[i]();
}
} ());
如何确保函数1在函数2之前执行?因为我遇到了一个问题,即我的函数2在函数1之前执行,结果不正确请命名第二个函数,不要将其排队,然后在放入队列的第一个函数末尾调用第二个函数
<script type="text/javascript">
// THIS IS FUNCTION 1
script_queue.push(function() {
// set the width of the thumbnail list to the sum of all the li widths
var thumbsWidth = 0;
$('#oneClipPlaylist li').each(func
…
secondFunc();
}
function secondFunc() {
// THIS IS FUNCTION 2
var allInputs = $('fieldset.categories input');
var categoryInputs = $('fieldset.categories input').not('#categoryAll');
var categoryAllInput = $('#categoryAll');
allInputs.click(function() {
var checkbox = $(this);
...
}
</script>
//这是功能1
脚本_queue.push(函数(){
//将缩略图列表的宽度设置为所有li宽度的总和
var thumbsWidth=0;
$('oneClipPlaylist li')。每个(func
…
secondFunc();
}
函数secondFunc(){
//这是功能2
var allInputs=$('fieldset.categories input');
var categoryInputs=$('fieldset.categories input')。而不是('categoryAll');
var categoryAllInput=$(“#categoryAll”);
所有输入。单击(函数(){
var复选框=$(此);
...
}
很久以前,我在很远很远的地方的一份工作上实现了一个类似的系统:)
我们的目的是在需要依赖项的其他脚本之前加载依赖项。例如,如果您以这种方式加载jQuery,则使用jQuery的任何其他脚本显然必须在加载jQuery之后才能执行。任何自定义JS对象都是如此
一些注意事项:
您的代码将在for循环中以正确的顺序执行
jQuery.Ajax()调用的settings
对象添加context
属性,并注册全局jQuery.ajaxComplete()
。上下文
属性的值应设置为脚本键(即“Script0”)
$jsload对象:
//让我们创建全局$jsload对象来处理JS脚本的排队
var$jsload=(函数(){
//让我们把内部事务保密
var scriptQueue={};
变量依赖项={};
var enqueue=function(键、scriptFunc、dependencyKey、isAjax){
脚本队列[键]={
dependencyKey:dependencyKey,
func:function(){
scriptFunc();
if(!isAjax)scriptCallBack(key);
}
};
添加DependencyItem(键,dependencyKey);
}
var addDependencyItem=函数(键,dependencyKey){
if(null==dependencyKey)返回;
//选中以添加到依赖项
if(null==依赖项[dependencyKey]| |“未定义”==依赖项[dependencyKey])
依赖项[dependencyKey]={};
//将此脚本添加到从属脚本
依赖项[dependencyKey][key]={isCompleted:false};
};
var checkDependency=函数(键,dependencyKey){
var obj=依赖项[scriptQueue[key].dependencyKey];
if(null!=obj&!obj.isCompleted)
返回false;
返回true;
};
var scriptCallBack=函数(键){
//脚本完成时调用;现在可以处理依赖项
if(null!=依赖项[键]){
for(依赖项中的var itemKey[key]){
scriptQueue[itemKey].func();
依赖项[key][itemKey].isCompleted=true;
}
}
};
//jsLoaderWithDependency对象以正确的顺序执行依赖脚本
//唯一可调用的公共方法是queue、ajax和processQueue
var jsLoaderWithDependency={
队列:函数(键、scriptFunc、dependencyKey){
排队(键、scriptFunc、dependencyKey、false)
<script type="text/javascript">
// Let's create global $jsload object to handle queueing of JS scripts
var $jsload = (function () {
// Let's make the internals private
var scriptQueue = {};
var dependencies = {};
var enqueue = function (key, scriptFunc, dependencyKey, isAjax) {
scriptQueue[key] = {
dependencyKey: dependencyKey,
func: function () {
scriptFunc();
if (!isAjax) scriptCallBack(key);
}
};
addDependencyItem(key, dependencyKey);
}
var addDependencyItem = function (key, dependencyKey) {
if (null == dependencyKey) return;
// Check to add to dependencies
if (null == dependencies[dependencyKey] || 'undefined' == dependencies[dependencyKey])
dependencies[dependencyKey] = {};
// add this script to dependent scripts
dependencies[dependencyKey][key] = { isCompleted: false };
};
var checkDependency = function (key, dependencyKey) {
var obj = dependencies[scriptQueue[key].dependencyKey];
if (null != obj && !obj.isCompleted)
return false;
return true;
};
var scriptCallBack = function (key) {
// Called when a script has finished; now ok to process dependencies
if (null != dependencies[key]) {
for (var itemKey in dependencies[key]) {
scriptQueue[itemKey].func();
dependencies[key][itemKey].isCompleted = true;
}
}
};
// The jsLoaderWithDependency object executes dependent scripts in the correct order
// The only callable public methods are queue, ajax, and processQueue
var jsLoaderWithDependency = {
queue: function (key, scriptFunc, dependencyKey) {
enqueue(key, scriptFunc, dependencyKey, false)
},
ajax: function (key, scriptFunc, dependencyKey) {
enqueue(key, scriptFunc, dependencyKey, true)
},
processQueue: function () {
for (var key in scriptQueue) {
if (checkDependency(key)) {
scriptQueue[key].func();
}
}
}
}
// This handler will execute at end of all Ajax requests;
// You can instead meake separate success/error handlers,
// for example, not to execute dependency scripts on error
// yet still show a message and/or log the error, etc.
$(document).ready(function () {
$(document).ajaxComplete(function (event, xhr, settings) {
scriptCallBack(settings.context);
});
});
return jsLoaderWithDependency;
})(); // Auto-execute self and init
</script>
<script type="text/javascript">
// Usage and test code
$jsload.ajax(
"Script0",
function () {
$.ajax({
// This is the only small change needed for dependency callback
context: "Script0",
// Standard ajax settings
url: "",
data: "ho ho ho",
dataType: "jsonp",
jsonp: "jsonp",
success: function (response, textS, xhr) {
console.log("Script 0 ( Ajax ) (no dependency) success");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log("Script 0 ( Ajax ) (no dependency) error");
}
});
console.log("Script 0 ( Ajax ) (no dependency) start");
},
null
);
$jsload.queue(
"Script1",
function () { console.log("Script 1 (dependency on Script 0, ajax callback)"); },
"Script0"
);
$jsload.queue(
"Script2",
function () { console.log("Script 2 (depends on Script 3)"); },
"Script3"
);
$jsload.queue(
"Script3",
function () { setTimeout(console.log("Script 3 Timeout (depends on Script 1)"), 1000); },
"Script1"
);
$jsload.queue(
"Script4",
function () { console.log("Script 4 (no dependency)");},
null
);
$jsload.processQueue();
</script>
// Adding basic functions to queue
script_queue.push(function () { console.log(1); });
script_queue.push(function () { console.log(2); });
script_queue.push(function () { console.log(3); });
script_queue.push(function () { console.log(4); });
script_queue.push(function () { console.log(5); });
// Let's do some Ajax!
script_queue.push(function () {
$.ajax({
type: "GET", url: "http://otherdomain.com/somePage.html",
data: "ho ho ho", dataType: "jsonp", jsonp: "jsonp",
success: function (response, textS, xhr) {
console.log("6 ajax finished success")
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log("6 ajax finished error")
}
});
console.log("6 ajax start");
});
// Let's throw in a timeout
script_queue.push(function () {
window.setTimeout(function () { console.log("7 with timeout") }, 1000);
});
script_queue.push(function () { console.log(8); });
script_queue.push(function () { console.log(9); });
script_queue.push(function () { console.log(10); });
// Process the funcs
(function () {
for (var i in script_queue) {
script_queue[i]();
}
} ());
</script>