What I’m after is a PHP-script which will provide a local copy of a javascript file stored on a different domain, e.g. JS-files used for tracking purposes, such as Google Analytics or, in my case, WordPress Stats.
The intention is to add it as follows in my own :
mysite.com/somepath/wpstats.js.php?w=201145
(where “w=year-week_number” is used in the same way as by wordpress.com. Their cache expiry for there original stats JS-file is one year – hence the JS-file will never be changed more often than once a week)
In my wpstats.js.php I want to download the correct file from wordpress.com when w=xx changes, otherwise I want to return it from a locally kept copy.
I can implement it with one internal variable called “w_current”, so that when a new visitor enters the site the second week w != w_current and it will trigger a new fetch. The problem is: how do I prevent race-conditions/parallelism problems that might occur when two website visitors simultaneously loads the website the first time the second week [1]?
[1] both apache-processes evaluate the w != w_current and starts two downloads of the (potentially) new version of the wpstats.js-file and both try to write it to the local copy (e.g. own_wpstats.js) which wpstats.js.php (in the normal case where a local copy already exists) will include:
if ($_GET["w"] == w_current) require("own_wpstats.js");
The main reason for doing this (performance possibly being another) is due to the fact that WordPress.com Stats injects (via DOM) an additional JS-tracking file from a third party, quantserve.com. In my locally kept “WP JS file” I will make sure this quantserve.com thing is excluded, but this is a separate programming challenge than the question I try to ask here. A search for “quantserve.com tracking cookie” gives many discomfortable results.
I wouldn’t worry TOO much about such a race condition. “Worst case” is you download the file twice.
But IF you are going to be doing ANY tracking of these files in a DB, then preventing the double download would be simple. Immediately before you start the download, check DB if file needs a refresh, log the refresh to the DB, and THEN do the download. Give the file a unique primary-key (site_url + file_name) and the second check before update will fail.