-
-
Save aziz/1249248 to your computer and use it in GitHub Desktop.
Optimise DOM insertion of cross-domain scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
( function ( win, doc ) { | |
// Google Analytics global variable | |
win._gaq = [ ['_setAccount','UA-XXXXX-X'], ['_trackPageview'], ['_trackPageLoadTime'] ]; | |
// Array of cross-domain script urls | |
var urls = [ | |
'//connect.facebook.net/en_US/all.js', // Facebook SDK | |
'//platform.twitter.com/widgets.js', // Twitter Widgets | |
'https://apis.google.com/js/plusone.js', // Google +1 Button | |
('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js' // Google Analytics | |
], | |
length = urls.length, | |
nodeName = 'script', | |
fragment = doc.createDocumentFragment(), // create container for DOM nodes | |
elem = doc.createElement( nodeName ), // create script element | |
temp; | |
while ( length -- ) { | |
temp = elem.cloneNode( false ); | |
temp.src = urls[ length ]; | |
temp.async = true; | |
fragment.appendChild( temp ); | |
} | |
// insert documentFragment before first script element | |
( temp = doc.getElementsByTagName( nodeName )[0] ).parentNode.insertBefore( fragment, temp ); | |
} ( this, document ) ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(w,d){ | |
w._gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview'],['_trackPageLoadTime']]; | |
var u=[ | |
'//connect.facebook.net/en_US/all.js', // Facebook SDK | |
'//platform.twitter.com/widgets.js', // Twitter Widgets | |
'https://apis.google.com/js/plusone.js', // Google +1 Button | |
('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js' // Google Analytics | |
],i=u.length,n='script',f=d.createDocumentFragment(),e=d.createElement(n),t;while(i--){t=e.cloneNode(false);t.async=t.src=u[i];f.appendChild(t);}(t=d.getElementsByTagName(n)[0]).parentNode.insertBefore(f,t); | |
}(this,document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment