在我的用例中,我使用外部和內聯JavaScript內容。我有以下結構。如何延遲內聯javascript加載時間?
app/
header.html
home.html
config-load.js
footer.html
home.html
包括header.html
和footer.html
。 header.html
文件包括config-load.js
。
config-load.js
一個Ajax調用來獲取基於來自golang後端舞臺CONFIGS。這可能有幾毫秒的延遲。
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>
而且我的配置,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天,但沒有運氣。
嘗試將'config-load.js'和'anotherscript.js'放入您的'footer.html' –