3.7. Handling Server Accessibility and Ad Blocking Problems

Although unlikely, it is possible that the Lat49 server might be inaccessible at times. If the server becomes unavailable while the application is running, then ads will no longer be updated, but no errors should result otherwise. However, if the server is down or blocked when an application starts up and the Lat49 script is not linked in, then javascript exceptions will be generated if the Lat49 object and its contained methods are not defined within the application code. To avoid such errors, it is advisable to wrap the calls to the Lat49 methods in try/catch statements. The following shows a part of the previous example with added wrapper code. The Lat49.initAds() method is wrapped in place in the <body> tag, while the Lat49.updateAdsByLatLon() method is wrapped in a function in the header.

Example 3-10. Embedded Ad with Wrapper Code

<!-- Include the Lat49 API script. -->
<script type='text/javascript' src='http://adserver.lat49.com/lat49/v0.10/lat49.js'>
</script>

<!-- Wrapped Lat49 method. -->
<script type='text/javascript'>
  updateAd = function(divId, x, y, z) {
    try {
      Lat49.updateAdByLatLon(divId, x, y, z);
    } catch(e) {}
  }
</script>

</head>

<!-- Initialize the Lat49 API on loading the body.
     Wrap the method call. -->
<body onload = "try{Lat49.initAds();}catch(e){}">
  <h2> Simple Lat49 test. </h2>
  <p>
    <!-- Fetch the ad when the link is clicked. -->
    Click the
    <a href="javascript:updateAd('adcontainer',85.051,-179.999,16)">link</a>
    to see the ad for tile (0,0,16):
  </p>

A simpler, but cruder, method of avoiding exceptions due to a missing Lat49 object is to create a dummy version with any required methods prior to linking the external Lat49 script from the server. In most cases, the external script will be linked in and override the dummy object. If the external script is inaccessible, the dummy methods will be used to avoid runtime exceptions. The following example shows how to do this for the previous simple example.

Example 3-11. Creating a Dummy Lat49 Object

<!-- Create a dummy Lat49 object first. -->
<script>
  var Lat49 = { initAds:function(){},
                updateAdByLatLon:function(){}
              };
</script>

<!-- Include the Lat49 API script. -->
<script type='text/javascript' src='http://adserver.lat49.com/lat49/v0.10/lat49.js'>
</script>