Showing posts with label fallback. Show all posts
Showing posts with label fallback. Show all posts

Thursday 5 February 2015

JS and CSS fall back using PHP

There are several solutions to JS and CSS out there on the web. I've tried quite a few, but I find that if I take my network connection out, they don't work. They don't fall back. Recently, maxcdn.bootstrapcdn.com went down causing websites, including my own, to suffer from a lack of bootstrap. Even though I'd put in some fall back code.
This prompted me to write the following code. Now I know I'll be criticised for using PHP as the solution, but if you've suffered as I have, you may consider this worth a try. Below is the PHP class followed by the HTML page which makes use of the class with the calls highlighted in red. In this case I'm calling Twitter Bootstrap.
callfallback.class.php
<?php
class callfallback
{
function __construct()
{

}

function getCSS($remote, $local)
{
if($this->testExists($remote) == TRUE)
{
echo '<link rel="stylesheet" href="'.$remote.'" />'.PHP_EOL;
}
else
{
echo '<link rel="stylesheet" href="'.$local.'" />'.PHP_EOL;
}
}

function getJS($remote, $local)
{
if($this->testExists($remote) == TRUE)
{
echo '<script src="'.$remote.'"></script>'.PHP_EOL;
}
else
{
echo '<script src="'.$local.'"></script>'.PHP_EOL;
}
}

function testExists($url)
{
$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 OK')
{  
 return TRUE;
}
else
{
 return FALSE;
}
}

function __destruct()
{

}
}
?>
index.html
<!DOCTYPE html>
<?php
require_once 'callfallback.class.php';
$cfb = new callfallback;
?>
<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">
  <title>Bootstrap Fallback Template</title>
  <?php
  $cfb->getCSS('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css','css/bootstrap.min.css');
  ?>
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
  </head>
  <body>
 
  <?php
  $cfb->getJS('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js','js/jquery-1.11.2.min.js');
  $cfb->getJS('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js','js/bootstrap.min.js');
  ?>
</body>
</html>