lib.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * Often used vanilla js functions, so that we don't need
  3. * to use all of underscore/jQuery
  4. */
  5. (function( undefined ) {
  6. "use strict";
  7. var v = ( window.VAMTAM = window.VAMTAM || {} ); // Namespace
  8. // Returns a function, that, as long as it continues to be invoked, will not
  9. // be triggered. The function will be called after it stops being called for
  10. // N milliseconds. If `immediate` is passed, trigger the function on the
  11. // leading edge, instead of the trailing.
  12. v.debounce = function( func, wait, immediate ) {
  13. var timeout;
  14. return function() {
  15. var context = this, args = arguments;
  16. var later = function() {
  17. timeout = null;
  18. if ( ! immediate ) func.apply( context, args );
  19. };
  20. var callNow = immediate && ! timeout;
  21. clearTimeout( timeout );
  22. timeout = setTimeout( later, wait );
  23. if ( callNow ) func.apply( context, args );
  24. };
  25. };
  26. // vanilla jQuery.fn.offset() replacement
  27. // @see https://plainjs.com/javascript/styles/get-the-position-of-an-element-relative-to-the-document-24/
  28. v.offset = function( el ) {
  29. var rect = el.getBoundingClientRect(),
  30. scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
  31. scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  32. return { top: rect.top + scrollTop, left: rect.left + scrollLeft };
  33. };
  34. // Faster scroll-based animations
  35. v.scroll_handlers = [];
  36. v.latestKnownScrollY = 0;
  37. var ticking = false;
  38. v.addScrollHandler = function( handler ) {
  39. requestAnimationFrame( function() {
  40. handler.init();
  41. v.scroll_handlers.push( handler );
  42. handler.measure( v.latestKnownScrollY );
  43. handler.mutate( v.latestKnownScrollY );
  44. } );
  45. };
  46. v.onScroll = function() {
  47. v.latestKnownScrollY = window.pageYOffset;
  48. if ( ! ticking ) {
  49. ticking = true;
  50. requestAnimationFrame( function() {
  51. var i;
  52. for ( i = 0; i < v.scroll_handlers.length; i++ ) {
  53. v.scroll_handlers[i].measure( v.latestKnownScrollY );
  54. }
  55. for ( i = 0; i < v.scroll_handlers.length; i++ ) {
  56. v.scroll_handlers[i].mutate( v.latestKnownScrollY );
  57. }
  58. ticking = false;
  59. } );
  60. }
  61. };
  62. window.addEventListener( 'scroll', v.onScroll, { passive: true } );
  63. // Load an async script
  64. v.load_script = function( src, callback ) {
  65. var s = document.createElement('script');
  66. s.type = 'text/javascript';
  67. s.async = true;
  68. s.src = src;
  69. if ( callback ) {
  70. s.onload = callback;
  71. }
  72. document.getElementsByTagName('script')[0].before( s );
  73. };
  74. })();