'How to get the status code for dynamically created script tag?
My code dynamically creates a <script> tag and attached it to the DOM tree. However, if for some reason the script fails to load, I need to figure out why. The event object passed to onerror callback does not show any information about why the script fails to load. I would like to at least get the status code of the request so I can determine if that's a 404 or 500. Is this possible?
In this question someone says that it is not possible to get the status code for <img> tag. I'm wondering if that also true for <script> tag.
Solution 1:[1]
You can try to fetch the script first and catch all errors information If fetch success u can load the script from the blob. U can find my full solution here
const loadScriptWithFetchFirst = function (url, includeCrossOrigin = true) {
return new Promise(function (resolve, reject) {
fetch(url,{ mode: includeCrossOrigin ? 'cors' : 'no-cors'})
.then((response) => {
if (!response.ok) {
reject(`Can't load script ${url} error: ${response.status}; ${response.statusText}`);
return null;
}
else {
return response.blob()}
})
.then((blob) => {
if (blob !== null) {
return;
}
const objectURL = URL.createObjectURL(blob);
const script = document.createElement('script');
script.src = objectURL;
if (includeCrossOrigin) {
script.crossOrigin = 'anonymous';
}
script.onload = function () {
resolve(true);
}
script.onerror = function (event) {
reject(event ? event : '')
};
document.head.appendChild(script);
})
.catch((e)=>{
reject(`Request failed: ${e}`);
})
});
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
