Last active
August 29, 2015 14:07
-
-
Save ethyde/8fb921db453200e0ba05 to your computer and use it in GitHub Desktop.
Optimised async loading of cross-domain scripts See also : http://css-tricks.com/thinking-async/
This file contains 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
// source : https://gist.github.com/necolas/1025811 | |
/* | |
* Updated to use the function-based method described in http://www.phpied.com/social-button-bffs/ | |
* Better handling of scripts without supplied ids. | |
* | |
* N.B. Be sure to include Google Analytics's _gaq and Facebook's fbAsyncInit prior to this function. | |
*/ | |
(function(doc, script) { | |
var js, | |
fjs = doc.getElementsByTagName(script)[0], | |
add = function(url, id) { | |
if (doc.getElementById(id)) {return;} | |
js = doc.createElement(script); | |
js.src = url; | |
js.async = 'async'; | |
id && (js.id = id); | |
fjs.parentNode.insertBefore(js, fjs); | |
}; | |
// Google Analytics | |
add('//www.google-analytics.com/analytics.js', 'ga'); | |
// Google+ button | |
add('https://apis.google.com/js/plusone.js'); | |
// Facebook SDK | |
add('//connect.facebook.net/en_US/all.js', 'facebook-jssdk'); | |
// Twitter SDK | |
add('//platform.twitter.com/widgets.js', 'twitter-wjs'); | |
// Livereload snippet | |
add('http://' + (location.host || 'localhost').split(':')[0] + ':8000/livereload.js?snipver=1', 'livereload'); | |
}(document, 'script')); |
This file contains 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 | |
_universalAsync : function(url, id){ | |
var js, | |
fjs = document.getElementById('basejs'), | |
add = function(href, idScript) { | |
if (document.getElementById(idScript)) {return;} | |
js = document.createElement('script'); | |
js.async = 'async'; | |
js.src = href; | |
idScript && (js.id = idScript); | |
fjs.parentNode.insertBefore(js, fjs); | |
}; | |
add(url, id); | |
} | |
// Call | |
UTIL._universalAsync('url', 'optionnal-id'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment