Fallback JavaScript library

The solution is a combination of the two JavaScript libraries and the calling HTML page using exception handling and dynamic HTML generation.

“Primary JavaScript library

function one() {
   return "1";
}

“Fallback” JavaScript library

function two() {
   return "2";
}

HTML file

<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Test</title>
    <link rev="made" href="mailto:www-validator@w3.org" />
    <link rev="start" href="./" title="Home Page" />
    <style type="text/css" media="all">@import "./base.css";</style>
  </head>

   <!-- fail to load the primary library1.js JavaScript library -->
   http://library.js

  <body>

   <!-- holder for dynamic HTML -->
   <div id="script_holder" />

   
      try {
       // try and use the primary script library (will fail)
       alert(one());
      } catch (exception) {
         // using the primary script library failed - fallback to secondary library
         var e = document.createElement("script");
         e.type = "text/javascript";
         e.src = "library2.js";
         document.getElementById("script_holder").appendChild(e);

         // set timeout to test that the fallback library was loaded
         setTimeout("doTest()", 100);
      }

      function doTest() {
         alert(two());
      }
   

  </body>
</html>

Published by

lekkim

Positive, competent, out-spoken, frank and customer focused architect and developer with a strong foundation in web, cloud and product development. I'm a strong advocate for API first and cloud based solutions and development. I have a knack for being able to communicate and present technically complicated matters in conference, customer and training settings. I've previously acted as team member and leader in a product organisation.