Skip to content

Instantly share code, notes, and snippets.

@tpage99
Last active June 22, 2022 16:57
Show Gist options
  • Save tpage99/08efebd0df3b8a2278b50a3b1f225c9c to your computer and use it in GitHub Desktop.
Save tpage99/08efebd0df3b8a2278b50a3b1f225c9c to your computer and use it in GitHub Desktop.
An example of how to load a script on scroll in Shopify
<script type="text/javascript">
window.addEventListener('scroll', scrollyScroll, false);
function scrollyScroll() {
let scrollPosition = 0;
scrollPosition = window.scrollY;
if (scrollPosition > 10) {
(function() {
var tidScript = document.createElement('script');
tidScript.type = 'text/javascript';
tidScript.async = true;
tidScript.src = 'https://scriptGoesHere';
(document.getElementsByTagName('body')[0]).appendChild(tidScript);
})();
stopIt();
}};
function stopIt (){
window.removeEventListener('scroll', scrollyScroll)
}
</script>
@tpage99
Copy link
Author

tpage99 commented Mar 3, 2021

the console.log(scrollPosition) was really just used to make certain that the event listener got removed window.onscroll == null and is not necessary.

@tpage99
Copy link
Author

tpage99 commented Jun 10, 2021

previous iterations didn't properly apply the listener event. had to update to remove, otherwise was firing over and over again. won't impact performance on speed tests, but likely could have caused user errors from firing repetitively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment