I would like to learn from the html below if link[rel=import] , link[rel=stylesheet] , img and script delayed / loaded / unsuccessful / interrupted without the need to add listeners in advance and at any time after the event
<!DOCTYPE html> <html> <head> <title>App</title> <meta charset="utf-8"> <link rel="import" href="template-bundle.html"> <link rel="stylesheet" href="bundle.css"> </head> <body> <header><img src="logo.png" alt="App logo"></header> <script src="./app-bundle.js"></script> </body> </html>
In other words: is there an interface that provides something similar to the Bluebird isPending() , isResolved() , isRejected() or regular ES6 promise methods?
Bonus question: can this be done using the Service Worker?
Since SW can intercept requests and know their status, I was wondering if I can implement an API that returns Promise, which
- waiting for the request to complete yet
- resolved if a
load event is fired - rejected if
error or aborted fired.
thanks for the help
Update and solution:
Thanks to the answers of @pritishvaidya and @ guest271314, I was able to come up with a viable solution using MutationObserver , which includes looking at the DOM to add resource nodes (link, img, script) and adding a promise for them, which will be resolved as described above
This works great with a single cadium that needs to be attached with a script tag in the <head> before any other resource. Here is an example
var resourceNodeSelector = 'link[href],script[src],img[src]'; function watchResource (n) { var url = n.href || n.src; if (!n.matches || !n.matches(resourceNodeSelector)) { return; } if (n.status) { return; } n.status = resourceObserver.promises[url] = new Promise(function (resolve, reject) { n.addEventListener('load', resolve); n.addEventListener('error', reject); n.addEventListener('abort', reject); n.addEventListener('unload', function (l) { delete resourceObserver.promises[url]} ); }); n.status.catch(function noop () {});
Once the observer is in place, any valid resource element must have the status property of the promise, which you can check at any time
document.querySelector('link').status.then(linkLoaded).catch(linkFailed)
ServiceWorker should have the most elegant solution possible, which is not associated with the use of the expensive querySelectorAll , since it can be programmed to intercept and track all resource requests and their status