Say i wanted load internally downloaded css and js files as an alternative to the following links if CDN was not working, how would i do it?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
CodePudding user response:
One way I can think of is to use the onerror
handler of the script tag, which will be called if the resource was not well loaded and after this you can load dynamically/manually the script from somewhere else.
setTimeout(() => {
if (window.jQuery) {
console.log('jQuerry is loaded from other source than CDN!');
}
}, 1000);
// Make sure you do a better way of assuring that your script is being loaded...
<script>
function onCDNFailed() {
console.log('CDN failed!');
// Loads from somewhere else..
const script = document.createElement('script');
script.onload = () => { console.log('script loaded!'); };
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
document.head.append(script);
}
</script>
<script src="https://ajax.googleapis.com/123.js" one rror="onCDNFailed()"></script>
Another way, is to just check after the CDN script if you have the resource you expect, and if not you can create a new script with different URL, something like this:
<script src="https://CDN/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="/your/jquery"></script>');
</script>
CodePudding user response:
To add the downloaded JavaScript / CSS file instead of using CDN you can replace your code with
<script type="text/javascript" src="./yourfilename.js"></script>
for JS
<link href="./yourfilename.css" rel="stylesheet">
for CSS
Here change the yourfile name appropriately with downloaded file name. This is the appropriate way if this didn't work check with licensing and policy of library you are using