Reputation: 193
How we can know with my application whether the user have blocked any external javascript those not allocated on my server, i.e. on my site jquery is loading from jquery.org and if user blocked that site then how can I show a message to that user to allow scripts from jquery.org.
I have found that this things is there on the site of stackoverflow.com when I do block stackoverflow shows me
"Stack Overflow requires external JavaScript from another domain, which is blocked or failed to load."
message, so my question is how can I get the idea of external scripts was loaded successfully or not?
Thanks in advance.
Upvotes: 1
Views: 2491
Reputation: 7338
Example code:
<script id="webfont-garamond-fallback" src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js" defer></script>
<script>
var webfont = document.querySelector('#webfont-garamond-fallback');
if (webfont !== null) {
webfont.addEventListener('load', function () {
WebFont.load({
google: {
families: ['EB Garamond:400,400italic']
}
});
});
}
</script>
Should work in all modern browsers and >= IE8
Upvotes: 0
Reputation: 5213
You could check the typeof
any function or variable defined in the external resource.
If a site require jQuery
and it was loaded from an external resource, simply run this check:
if (typeof jQuery === "undefined"){
console.log("jQuery is not defined");
}
Put your check just before the first use of jQuery.
Upvotes: 0
Reputation: 3247
In addition to answers, <script>
element has onload
and onerror
events, as many other elements. Here's info about browsers compatibility and here's question about how to make it work in old IE.
Upvotes: 2
Reputation: 1993
Perform something with your external js. For example let your scripts add a specific class to the body:
<body class="js-file-1-loaded js-file-2-loaded ...">
With that you can always check weather something has been loaded or not.
Upvotes: -1
Reputation: 816302
Simplest solution: Put some code after the external script which tests whether the symbol it introduces (e.g. jQuery
) exists.
<script src="url-to-jquery"></script>
<script>
if (!window.jQuery) {
alert('jQuery could not be loaded');
}
</script>
But that could become tedious if you have many external references. In that case, you might want to build upon a resource loader, such as https://github.com/cujojs/curl.
Upvotes: 0