can3p (can3p) wrote in changelog,
can3p
can3p
changelog

[ljcom] r10683: LJSUP-9143: Problems with loading button...

Committer: dpetrov
LJSUP-9143: Problems with loading buttons in LJ-like
A   trunk/htdocs/js/jquery/jquery.vkloader.js
Added: trunk/htdocs/js/jquery/jquery.vkloader.js
===================================================================
--- trunk/htdocs/js/jquery/jquery.vkloader.js	                        (rev 0)
+++ trunk/htdocs/js/jquery/jquery.vkloader.js	2011-06-23 06:55:31 UTC (rev 10683)
@@ -0,0 +1,98 @@
+/*!
+ * LiveJournal loader for vkontakte like buttons.
+ *
+ * Copyright 2011, dmitry.petrov@sup.com
+ *
+ * VK script is often loaded with notable delay, so
+ * plugin just loads it after the page rendering and
+ * allows to display page faster.
+ *
+ */
+( function( $ ) {
+
+	if( $.VK ) { return; }
+
+	$.VK = {};
+
+	var onloads = [];
+		buttons = [],
+		onloadPassed = false,
+		scriptLoaded = false,
+		scriptLoading = false;
+
+	/**
+	 * Public API
+	 *
+	 * @namespase $.VK
+	 */
+	$.VK = {
+
+		/**
+		 * Init VK object after the script load.
+		 *     Function passes all option to the VK.init
+		 *  @param {Object} options
+		 */
+		init: function( options ) {
+			onloads.push( function() {
+				VK.init( options );
+			} )
+		},
+
+		/**
+		 * Add button to init after script load.
+		 *    If this method was called after the page load, and script wasn't downloaded yet,
+		 *    it will trigger downloading.
+		 */
+		addButton: function( elementId, options ) {
+			buttons.push( {
+				id: elementId,
+				options: options
+			} );
+
+			if( onloadPassed && !scriptLoading ) {
+				if( scriptLoaded ) {
+					initButtons();
+				} else {
+					loadscript( initButtons );
+				}
+			}
+		}
+	}
+
+	function initButtons() {
+		for( var i = 0; i < buttons.length; ++i ) {
+			VK.Widgets.Like( buttons[ i ].id, buttons[ i ].options );
+		}
+
+		buttons = [];
+	}
+
+	function loadScript( onload ) {
+		onload = onload || $.noop;
+		scriptLoading = true;
+
+		$.getScript( 'http://userapi.com/js/api/openapi.js?31', function() {
+			scriptLoading = false;
+			scriptLoaded = true;
+			for( var i = 0; i < buttons.length; ++i ) {
+
+				onloads[ i ]();
+			}
+			onloads = [];
+			onload();
+		} );
+	}
+
+	jQuery( function() {
+		//Do not download the script if the widgets were not added yet.
+		if( buttons.length ) {
+			//Do not load the script directly after the page load.
+			//We don't want to delay other onload functions somehow.
+			setTimeout( function() {
+				loadScript( initButtons );
+			}, 500 );
+		}
+		onloadPassed = true;
+	} );
+
+} ) ( jQuery );

Tags: can3p, js, ljcom
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments