Last active
February 19, 2019 02:29
-
-
Save jonaskuske/2f967b4fb95bd862a9c3f26e49d41113 to your computer and use it in GitHub Desktop.
Smallest way to load smoothscroll polyfills
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
// Loading "smoothscroll-polyfill" & "smoothscroll-anchor-polyfill" + setting scroll-behavior to smooth in 247 bytes: | |
((d,s,u)=>{d.documentElement.setAttribute('style','scroll-behavior:smooth');let i=s=>{let e=d.createElement('script');e.src=s;d.head.append(e)};i(u+s+`-polyfill/dist/${s}.min.js`);i(u+s+'-anchor-polyfill')})(document,'smoothscroll','//unpkg.com/') | |
// Readable version: | |
((doc, name, cdn) => { | |
// Set scroll-behavior, setAttribute so it works in browsers that don't recognize the property | |
doc.documentElement.setAttribute('style', 'scroll-behavior: smooth;'); | |
// Function to insert scripts... | |
const insertScript = url => { | |
const scriptElement = doc.createElement('script'); | |
scriptElement.src = url; | |
doc.head.append(scriptElement); | |
} | |
// Insert both polyfills | |
insertScript(`${ cdn }${ name }-polyfill/dist/${ name }.min.js`); | |
insertScript(`${ cdn }${ name }-anchor-polyfill`); | |
})(document, 'smoothscroll', 'https://unpkg.com/') | |
// ES5 (262 bytes): | |
!function(d,s,u){d.documentElement.setAttribute('style','scroll-behavior:smooth');function i(s){var e=d.createElement('script');e.src=s;d.head.appendChild(e)};i(u+s+'-polyfill/dist/'+s+'.min.js');i(u+s+'-anchor-polyfill')}(document,'smoothscroll','//unpkg.com/') | |
// If we can live with the unminified version of "smoothscroll-polyfill" we can get down to 230 bytes: | |
((d,s,u)=>{d.documentElement.setAttribute('style','scroll-behavior:smooth');let i=s=>{let e=d.createElement('script');e.src=s;d.head.append(e)};i(u+s+'-polyfill');i(u+s+'-anchor-polyfill')})(document,'smoothscroll','//unpkg.com/') | |
// ...but now we saved 17 bytes just to load a huge unminified polyfill and ruin the savings :D |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment