Sunday, June 12, 2011

Sharethis getScript timing and interval retries

I recently posted on some sharethis work I did. Well, now I had an issue with HTTP and HTTPS and needed to switch the script load given the protocol in use. I gave the getScript a go. Problem was that the script load finishes in a callback or thread, and timing is now an issues for later events that depend on the Sharethis code to be loaded.

In my last post, I mentioned the Ajax and the button loading setup process. This was failing because the main Sharethis object didn't exist from time to time with the asynchronous loading of getScript.

Oddly, the reference to the stButton object was throwing an undefined exception even though I had proper checks in place to ensure that it was defined before I acted on it. Since this didn't work, I was forced to just wrap the stButton reference in a try catch block. On the exception was when the asynchronous script load was not completed. In the catch block, I was forced to add a timer to keep retrying to execute the button setup code when it was ready.

   if (stButtons && typeof(stButtons) != undefined){
} catch (stException){
   var intervalId = window.setInterval(function(){
   } catch(stException){}
}, 2000);

The above code tries to run the "locateElements" function, when it fails or is not defined, then the window is given a function call to retry every 2 seconds. When successful, that process is ended.

See the setInterval and clearInterval methods.

Classic timing issue of threads, I just didn't think about it at the time. The call to the "stButtons.locateElements" could be placed in the getScript callback as well.

No comments:

Share on Twitter