Fetching JavaScript libraries with PHP

Recently jQuery's developers released the new 1.5 version of this popular JavaScript library. For a couple of days this version was not available on Google's CDN and even now is not listed on their pages, though as I'm writing this post the new URL is active. Anyway, if a developer wanted to include the new version on his/her documents, he basically had to manually check if the newer version actually existed in the wild. So I devoted some of my spare time in writing a really basic class that retrieves the current available version of a JavaScript library.

This class is as follows:

class JSLibraryLoad
    protected $_baseURL;
    protected $_library;
    protected $_version;
    protected $_fallbackVersion;
    public function __construct($baseURL, $library, $version, $fallbackVersion)
       $this->_baseURL = $baseURL; 
       $this->_library = $library;
       $this->_version = $version;
       $this->_fallbackVersion = $fallbackVersion;
    protected function _parseVersion($version)
        if(preg_match('/(\d\.)+/', $version)) {
            $last_version = preg_replace('/\.\d$/', '', $version);
        return $last_version;
    public function fetchLibrary()
        header('Content-Type: text/javascript');
        $library_ver = $this->_parseVersion($this->_version);
        $full_URL = $this->_baseURL . $library_ver . '/' . $this->_library;
        $alt_URL = $this->_baseURL . $this->_fallbackVersion . '/'. $this->_library;
        if(file_get_contents($full_URL)) {
            $output = file_get_contents($full_URL);
            return $output;
        } else {
            $output = file_get_contents($alt_URL);
            return $output;

As you can see, it's very, very simple. In its essence, this class tries first to fetch the latest version of a JavaScript library and, if it fails, loads the latest stable release. An example:

$library = new JSLibraryLoad(
echo $library->fetchLibrary();

The use of regular expressions in this class it's not 100% efficient, because it doesn't take into account the case of libraries having always a pattern like 1.x in their version number. Further, a more robust exception handling routine would be required while trying to load the major version. Anyway, feel free to improve it, as you like.


Fetching the latest jQuery version

Leave a Reply

Note: Only a member of this blog may post a comment.