Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

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:

  • For jQuery Validate, I find conflicting information: this topic suggests one can do if (window.validator), this one suggests one needs if(typeof $().validate == 'undefined'). What is the difference between these, and why would I need one over the other?
  • For less popular libraries, e.g. balanceText, how should I find out if the library was loaded succesfully?

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

question from:https://stackoverflow.com/questions/65910886/how-does-one-test-if-some-javascript-library-was-loaded-succesfully-from-cdn

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...