Skip to content
Advertisement

Can you add if statements in case a src item doesn’t appear with a return status of 404

I’m trying to use two script hosts in case one doesn’t show but my catch statement doesn’t seem to be catching status 404 errors when I purposefully mess up the url. Here’s the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/p5@1.0.0/lib/p5.js"></script>
    <script onerror="error()" ></script>
    <script src="blockman.js"></script>
    <script src="https://craigapphostl.w3spaces.com/scripts.js"></script>
    <title>Document</title>
    <button onclick="f()">Test</button>
</head>
<body>
</body>
<script>
    function error(){
    //added l's on the end to both script host links
    alert("some thing hs went wrong trying back up host")
    } 
   
    try{
      var t=document.createElement("script")
    t.setAttribute("src","https://vdkhiyrhibxzmpiophft.w3spaces.com/scripts.js") 
  document.body.appendChild(t);
    }
    catch(e){
      alert(e)
    }
    
</script>
</html>

Advertisement

Answer

This type of error cannot be catched with try...catch. Instead, listen on the error event.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/p5@1.0.0/lib/p5.js"></script>
  <script onerror="error()"></script>
  <script src="blockman.js"></script>
  <script src="https://craigapphostl.w3spaces.com/scripts.js"></script>
  <title>Document</title>
  <button onclick="f()">Test</button>
</head>
<body>
</body>
<script>
  function error() {
    //added l's on the end to both script host links
    alert("some thing hs went wrong trying back up host")
  }
  var t = document.createElement("script");
  // Alerts "Error loading script" if there was an error
  t.onerror = err => alert("Error loading script");
  t.setAttribute("src", "https://vdkhiyrhibxzmpiophft.w3spaces.com/scripts.js");
  document.body.appendChild(t);
</script>
</html>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement