kebugcheck
kebugcheck

Reputation: 173

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.

Upvotes: 1

Views: 1424

Answers (2)

Gennadiy Utkin
Gennadiy Utkin

Reputation: 21

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}`);
            })
});

};

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

According to XML.com,

The most notable downside [of the script tag] is that it cannot handle errors gracefully. If the web service returns an invalid JavaScript statement to the script tag, a JavaScript error will be generated. If the web service returns invalid JSON wrapped inside a callback function, a JavaScript error will be returned when the invalid JSON data is passed to the callback function. If your web service returns an HTTP return code other than 200 (successful), then the script tag will silently fail.

So no, there is no way to determine a non-200 status code of a dynamic <script> tag.

Having said that, if you use an AJAX request, you will be able to get both the status code and error:

enter image description here

Upvotes: 2

Related Questions