Premise: I\'ve found these two answers but I don\'t understand how I can sistematically apply it for many libraries:
Detect and log when external Ja
Just add an onerror handler to the tag. This can call a fallback, give the user a message etc.
Using a non-existing url will here pop up an alert:
<link
onerror="alert('woa, error')"
rel="stylesheet"
href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.2/angular material.min.cssx"
>
For custom function, just define a script block in the header before the link tags so you can call a custom function:
<script>
function myFunction() {alert("whaaaa.."); /* or something more meaningful */}
</script>
<link
onerror="myFunction()"
rel="stylesheet"
href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.2/angular material.min.cssx"
>
What makes most sense in this case, is a feature check. Test for the existence of JS objects or JS methods to find out if a JS library has been loaded and test for the existence of certain CSS rules to find out if a CSS file has been loaded.
See this Fiddle for a demo.
See also below for the most relevant parts of the code.
How to find out whether a certain CSS rule exists :
window.CSSRuleExists = function(rule) {
var sSheetList = document.styleSheets;
for (var sSheet = 0; sSheet < sSheetList.length; sSheet++) {
var ruleList = sSheetList[sSheet].cssRules;
for (var item = 0; item < ruleList.length; item ++){
if(ruleList[item].selectorText === rule) {
return true;
}
}
}
return false;
}
How to find out whether a certain JS method exists :
window.JSFunctionExists = function(method, parent) {
parent = (typeof parent === typeof undefined) ? window : parent;
return (typeof parent[method] === 'function');
}
How to find out whether a certain JS object exists :
window.JSObjectExists = function(object, parent) {
parent = (typeof parent === typeof undefined) ? window : parent;
return (typeof parent[object] === 'object');
}
How to use these functions :
function process() {
el1.innerHTML = CSSRuleExists('button.special');
el2.innerHTML = JSFunctionExists('CSSRuleList');
el3.innerHTML = JSObjectExists('location');
}
based on the accepted answer. Just tested on Firefox, Edge (the new one), Chrome and Opera.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
<script>
function CssOrScriptFallBack(el) {
if (el instanceof HTMLScriptElement || el instanceof HTMLLinkElement) {
let Url = el.getAttribute('data-fallback');
if (Url) {
let attr = el instanceof HTMLScriptElement ? 'src' : 'href';
el.setAttribute(attr, Url);
}
}
}
</script>
<link href='https://not-working-cdn/file-name.min.css' rel='stylesheet'
onerror='CssOrScriptFallBack(this)'
data-fallback='/css/file-name.min.css' />
</head>
<body>
...
</body>
</html>