infinity_newsfeed.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * @var $this \yii\web\View
  4. * @var $model \app\models\News
  5. */
  6. ?>
  7. <div class="list w-100">
  8. </div>
  9. <script>
  10. let lastPostId = null;
  11. let targetEl = null;
  12. let infinityNewsAmount = 0;
  13. window.processInfinityNewsFeed = (el) => {
  14. targetEl = el;
  15. let targetElementVisible = false;
  16. window.handleInfinityNewsFeed = (e) =>
  17. {
  18. if(elementInViewport(targetEl) && !targetElementVisible){
  19. targetElementVisible = true;
  20. const request = new XMLHttpRequest();
  21. const url = "/news/infinity-newsfeed?last_post_id=" + lastPostId + "&post_id=<?=$model->id?>" + "&amount=" + infinityNewsAmount;
  22. request.open('GET', url);
  23. request.setRequestHeader('Content-Type', 'application/x-www-form-url');
  24. request.addEventListener("readystatechange", () => {
  25. if (request.readyState === 4 && request.status === 200) {
  26. let data = JSON.parse(request.responseText);
  27. document.getElementById("infinity_newsfeed").getElementsByClassName('list')[0].insertAdjacentHTML('beforeend',data.html);
  28. const scriptTmpStorage = document.createElement('div');
  29. scriptTmpStorage.innerHTML = data.html;
  30. const scripts = scriptTmpStorage.getElementsByTagName('script');
  31. if(scripts.length > 0 ){
  32. for(let i = 0;i < scripts.length; i++){
  33. console.log('Evalating ' + scripts[i].innerHTML)
  34. eval(scripts[i].innerHTML)
  35. }
  36. }
  37. lastPostId = data.id;
  38. infinityNewsAmount++;
  39. targetElementVisible = false;
  40. window.processInfinityNewsFeed(document.getElementById("post-"+data.id));
  41. }
  42. });
  43. request.send();
  44. }
  45. }
  46. }
  47. let commentsElement = document.getElementById('comments');
  48. processInfinityNewsFeed(commentsElement);
  49. window.elementInViewport = (el) => {
  50. if(el === 'undefined') return false;
  51. var rect = el.getBoundingClientRect();
  52. return (
  53. rect.top > 0 &&
  54. (rect.top - window.innerHeight) <= 0
  55. );
  56. }
  57. if (window.addEventListener) {
  58. addEventListener('DOMContentLoaded', handleInfinityNewsFeed, false);
  59. addEventListener('load', handleInfinityNewsFeed, false);
  60. addEventListener('scroll', handleInfinityNewsFeed, false);
  61. addEventListener('resize', handleInfinityNewsFeed, false);
  62. } else if (window.attachEvent) {
  63. attachEvent('onDOMContentLoaded', handleInfinityNewsFeed); // Internet Explorer 9+ :(
  64. attachEvent('onload', handleInfinityNewsFeed);
  65. attachEvent('onscroll', handleInfinityNewsFeed);
  66. attachEvent('onresize', handleInfinityNewsFeed);
  67. }
  68. </script>