gpt4 book ai didi

javascript - 图表 - 实现有序、异步脚本加载?

转载 作者:行者123 更新时间:2023-12-02 18:50:54 25 4
gpt4 key购买 nike

为了提高性能,有多种方法可以异步加载 JavaScript,如 SO post. 所示。

但是,一般来说,如果您需要的话,这些方法不会保留顺序,例如依赖项。

您可以通过哪些方式获得异步加载的好处,同时在需要时保留顺序。

主干依赖关系就是一个很好的例子。

(require.js,jquery.js)->backbone.js

库中是否有可实现此目的的 promise 或队列的实现?

它看起来不像head.js尚未使用 Promise 或队列。

最佳答案

简单的解决方案:使用Promises.ajax jQuery 从 1.5 版开始提供了 Promise。

如果你不能使用第三方库,你可以这样做:

var resourceData = {};
var resourcesLoaded = 0;

function loadResource(resource, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var state = this.readyState;
var responseCode = request.status;

if(state == this.DONE && responseCode == 200) {
callback(resource, this.responseText);
}
};

xhr.open("get", resource, true);
xhr.send();
}

//Assuming that resources is an array of path names
function loadResources(resources) {
for(var i = 0; i < resources.length; i++) {
loadResource(resources[i], function(resource, responseText) {

//Store the data of the resource in to the resourceData map,
//using the resource name as the key. Then increment the
//resource counter.
resourceData[resource] = responseText;
resourcesLoaded++;

//If the number of resources that we have loaded is equal
//to the total number of resources, it means that we have
//all our resources.
if(resourcesLoaded === resources.length) {
//Manipulate the data in the order that you desire.
//Everything you need is inside resourceData, keyed
//by the resource url.
...
...
}
});
}
}

关于javascript - 图表 - 实现有序、异步脚本加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15840664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com