user1111929
user1111929

Reputation: 6099

How does one test if some javascript library was loaded succesfully from CDN?

When downloading javascript files from a CDN, I'd like to provide a local fallback. It's however not always obvious to me how to test if a certain load has succeeded.

For some popular things this is well documented in other StackOverflow questions, e.g. for Bootstrap one just tests if (window.jQuery), if (window.Popper), if ($.fn.modal) for its three parts respectively. However, for other libraries this is less obvious:

A general answer/approach would be perfect, but if that's not feasible, I'd be grateful for an answer on these two libraries.

Upvotes: 1

Views: 1660

Answers (1)

Soc
Soc

Reputation: 7780

If you're using loading the script yourself, you can use the onerror event on the script element to see if the script loaded instead of checking for side effects. Example:

<script>
function cdnLoaded() {
  console.log('loaded');
}

function cdnError() {
  console.log('not loaded');
  // do error handling here
}
</script>

<script onload="cdnLoaded()" onerror="cdnError()" async src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script onload="cdnLoaded()" onerror="cdnError()" async src="https://unpkg.com/nothing-here.js"></script>

Upvotes: 5

Related Questions