gpt4 book ai didi

javascript - 如何延迟内联 javascript 加载时间?

转载 作者:行者123 更新时间:2023-11-30 15:56:45 25 4
gpt4 key购买 nike

在我的用例中,我同时使用了外部和内联 javascript 内容。我有以下结构。

  app/
header.html
home.html
config-load.js
footer.html

home.html 包括header.htmlfooter.htmlheader.html 文件包含 config-load.js

config-load.js 进行 ajax 调用以从 golang 后端获取基于阶段的配置。这可能会有几毫秒的延迟。

home.html 中有一些内联脚本,它使用 config-load.js ajax 调用收集的配置。

因此 config-load.js ajax 调用必须在内联脚本加载之前完成。但它正在以相反的方式加载。

我尝试使用 while 循环来延迟内联脚本的加载时间,如下所示,

while(configReceived == false)
{
setTimeout(function(){
console.log("waiting for config");
}, 2000);
}
if(configReceived)
{
//process configs
}

但这会阻塞线程。该页面卡在 while 循环中。还有其他方法可以实现吗?

编辑 1:这是内联脚本内容,

  <script type="text/javascript">
window.onload = function() {
time = new Date($.now());
var tagsArray = ["C", "C++", "Go", "Ruby"];
//var tagsArray = [];
requestJSON = '{"Method":"GET","AppName":"Web-app","ServiceURL":"'+endpoints.Tags.HTTPEndpoint.URL+'","Properties":null,"Object":"","Timestamp":"'+time+'"}'
$.ajax({
type: "GET",
url: endpoints.Tags.HTTPEndpoint.URL,
data: requestJSON,
processData: false,
contentType: "application/json;",
dataType: "json",
async: false,
success: function(data){
console.log("tags retrieved successfully info updated successfully")
console.log("Tags ", data.Object)
tagsArray = data.Object
},
failure: function(errMsg) {
console.log("Error occured in getting tags ", errMsg)
}
});
$("#myTags").tagit();
$("#tags").tagit({
fieldName: "tagsName", // The name of the hidden input field
availableTags: tagsArray,
allowSpaces:true,
caseSensitive:false,
removeConfirmation:true,
placeholderText:"Tags",
tagLimit: 5,
allowDuplicates: false,
singleField: true, // Use a hidden input element with the fieldName name
singleFieldDelimiter: ',', // Optional, default value is same.
onlyAvailableTags: false
});
}
</script>

我的 config-load.js 如下所示,

//////////////////////////////////////////////////////////
// code block to get the service endpoints by stage starts
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
endpoints = JSON.parse(xhr.responseText);
console.log("server endpoints be ", endpoints);
configReceived = true;
}
}
xhr.open("GET", "/config", true);
try {
xhr.send();
} catch (err) {
// handle error
console.log("Error occured in getting the service endpoints. This may break all ajax services");
}
// code block to get the service endpoints by stage ends
////////////////////////////////////////////////////////

我已经尝试了最后 3 天,但没有成功。

最佳答案

“while 循环”是同步的,这意味着它会阻塞线程并使整个应用程序卡住。

Javascript async 脚本的执行顺序没有保证,所以你应该使用“回调”或者在 ES6 中你可以使用 promise,ES7 中你可以使用 async,await。

无论如何,更好的方法是将您的 config-load.js javascript 代码包装在一个函数中,如果您使用 Jquery 的 ajax api,代码可能如下所示:

function loadConfigAjax(callback){
$.ajax({url: "http://myconfig", success: function(config){
callback(config)
}});
}

在你的内联 javascript 中可能看起来像这样

<script type="text/javascript">
window.onload = function() {
var configReceived = function(config){
//process configs
};
// pass the configReceived as callback
// so that configReceived function will always be invoked after config received
loadConfigAjax(configReceived);
}
</script>

关于javascript - 如何延迟内联 javascript 加载时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38407711/

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