I'm working on making a small advertisement script.
An ad is inserted on a page, by inserting the following script:
<script class="gd-ad-script" src="http://domain.dk/ads/gdAds.js?adID=1&x=auto&y=auto&loadAd=?"></script>
<script class="gd-ad-script" src="http://domain.dk/ads/gdAds.js?adID=2&x=auto&y=auto&loadAd=?"></script>
<script class="gd-ad-script" src="http://domain.dk/ads/gdAds.js?adID=3&x=auto&y=auto&loadAd=?"></script>
This should insert 3 ads on the page. Since the adID is set, it should not select a random ad, but a specific ad.
Now here is my script:
/*! jQuery v1.8.3 jquery.com | jquery.org/license */
// * jQuery libary here * //
$(document).ready(function(){
var count = 0;
var JSONurl = 'http://domain.dk/ads/loadAd.php?callback=?';
$('.gd-ad-script').each(function(){
var adSrc = $(this).attr('src');
var adID = adSrc.substring(adSrc.indexOf('?adID=') + 6, adSrc.indexOf('&x='));
var x = adSrc.substring(adSrc.indexOf('&x=') + 3, adSrc.indexOf('&y='));
var y = adSrc.substring(adSrc.indexOf('&y=') + 3, adSrc.indexOf('&loadAd=?'));
var JSONdata = 'domain=' + window.location.hostname + '&adID=' + adID + '&xres=' + x + '&yres=' + y;
$(this).attr('id', 'add-current-ad' + adID);
$.getJSON(JSONurl, JSONdata, function(serverResponse) {
++count;
if (count == 1) {
alert(adID); // Comment this line out, unless testing
$('head').prepend(serverResponse.cssReset);
$(serverResponse.adContent).insertAfter('#add-current-ad' + adID);
$('#add-current-ad' + adID).remove();
}
});
});
});
Now, I would expect the page with the three scripts on, giving med three alert boxes in sequential order. 1, 2, 3. However, it is completely random because it all depends on how fast the server response from my ajax call is.
The results is, that the ads are placed in random order instead of 1, 2, 3.
My first thought was to use .gd-ad-script:first as selector, so that each script would process only one ad but then I realized that it would require me to somehow delay everything until the first ad script is removed, which is undesirable...
Any good advices?