栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

jQuery:按顺序加载脚本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jQuery:按顺序加载脚本

您可以通过使用回调函数

$.getscript()
作为递归函数调用在前一个完成加载后加载每个。

//setup array of scripts and an index to keep track of where we are in the processvar scripts = ['script1.js','script2.js','script3.js'],    index   = 0;//setup a function that loads a single scriptfunction load_script() {    //make sure the current index is still a part of the array    if (index < scripts.length) {        //get the script at the current index        $.getscript(scripts[index], function () { //once the script is loaded, increase the index and attempt to load the next script console.log('Loaded: ' + scripts[index]); index++; load_script();        });    }}

在您的代码中发生的是,脚本是同时被请求的,并且由于它们是异步加载的,因此它们以随机顺序返回并执行。

更新资料

我尚未对此进行测试,但是如果脚本是在本地托管的,则可以尝试以纯文本格式检索它们,然后将所有代码存储在变量中,直到它们全部加载完毕为止,然后可以按顺序评估脚本:

var scripts   = ['script1.js','script2.js','script3.js'],    //setup object to store results of AJAX requests    responses = {};//create function that evaluates each response in orderfunction eval_scripts() {    for (var i = 0, len = scripts.length; i < len; i++) {        eval(responses[scripts[i]]);    }}$.each(scripts, function (index, value) {    $.ajax({        url      : scripts[index],        //force the dataType to be `text` rather than `script`        dataType : 'text',        success  : function (textscript) { //add the response to the `responses` object responses[value] = textscript; //check if the `responses` object has the same length as the `scripts` array, //if so then evaluate the scripts if (responses.length === scripts.length) { eval_scripts(); }        },        error    : function (jqXHR, textStatus, errorThrown) {  }    });});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418243.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号