0

Could somebody suggest me a way for loading css or javascript file conditionally i.e only if url is accessible?

for example on my page I have the following files:

<html>
...
<link rel="stylesheet" type="text/css" href="https://service.test/css/a.css"/>
<script type="text/javascript" src="https://services.test/js/a.js"></script>
...
</html>

Is there any way to check if https://service.test/css/a.css is accessible then if yes load this resource (same for https://services.test/js/a.js)?

showdev
  • 28,454
  • 37
  • 55
  • 73
t99ver
  • 23
  • 3

1 Answers1

0

You could try something like this. but it will only work for the stylesheets that are in head section.

<html>
<link rel="stylesheet" type="text/css" href="https://service.test/css/a.css"/>
<body>

</body>

<script>
// you will have to manuall define the pairs (keys are stylesheets and values are scripts you want to load)
const pairs = {
    "https://service.test/css/a.css": "https://services.test/js/a.js"
}

let styles = document.querySelectorAll("link[rel='stylesheet'][type='text/css'][href]");

styles.forEach(s => {
  if(pairs[s.href]){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = pairs[s.href];    
    document.getElementsByTagName('head')[0].appendChild(script);
  }
});
</script>
</html>
anees
  • 1,777
  • 3
  • 17
  • 26