Guest User

Untitled

a guest
Feb 16th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. 'use strict';
  2.  
  3. /**
  4. * `callWhenHrefChanges(callback)`
  5. *
  6. * Schedules a callback to be called whenever the browser's URL
  7. * (`window.location.href`) changes.
  8. *
  9. */
  10. let callWhenHrefChanges = (() => {
  11.  
  12. // =========================================================================
  13.  
  14. // Stores previous href location.
  15. let prev = '';
  16.  
  17. // Stores functions to be called
  18. let functions = new Array();
  19.  
  20. // =========================================================================
  21.  
  22. /** Checks if the URL has changed. Updates the `prev` if so. */
  23. function hasHrefChanged() {
  24. let hasChanged = false;
  25. const href = window.location.href;
  26.  
  27. if ( href != prev ) {
  28. prev = href;
  29. hasChanged = true;
  30. }
  31.  
  32. return hasChanged;
  33. }
  34.  
  35. /** Call every function scheduled to be called on URL changes. */
  36. function callFunctions() {
  37. functions.forEach( f => f() );
  38. }
  39.  
  40. /** Schedule a function to be called when the browsers URL changes. */
  41. function callWhenHrefChanges(callback) {
  42. functions.push(callback);
  43. }
  44.  
  45. // == Main Async Loop ======================================================
  46.  
  47. setInterval(() => {
  48.  
  49. if ( hasHrefChanged() ) {
  50. callFunctions();
  51. }
  52.  
  53. }, 250);
  54.  
  55. // =========================================================================
  56.  
  57. return callWhenHrefChanges;
  58.  
  59. })();
Add Comment
Please, Sign In to add comment