Behance - fetch lazy-load images immediately

Fetch lazy-load images immediately at document load

当前为 2015-05-03 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Behance - fetch lazy-load images immediately
  3. // @description Fetch lazy-load images immediately at document load
  4. // @include https://www.behance.net/*
  5. // @version 1.0.4
  6. // @namespace wOxxOm.scripts
  7. // @author wOxxOm
  8. // @license MIT License
  9. // @run-at document-start
  10. // ==/UserScript==
  11.  
  12. window.addEventListener('DOMContentLoaded', function(e) {
  13. processNodes(null, document.querySelectorAll('.js-picture-lazy'));
  14. setMutationHandler(document.body, '.js-picture-lazy', processNodes);
  15. });
  16.  
  17. function processNodes(observer, nodes) {
  18. for (var i=0, len=nodes.length, n, img; i<len && (n=nodes[i]); i++) {
  19. if (img = n.querySelector('img')) {
  20. img.src = img.dataset.src;
  21. img.removeAttribute('width');
  22. img.removeAttribute('height');
  23. img.removeAttribute('style');
  24. }
  25. var picture = document.createElement('picture');
  26. while (n.firstElementChild)
  27. picture.appendChild(n.removeChild(n.firstElementChild));
  28. n.parentNode.replaceChild(picture, n);
  29. n.remove();
  30. }
  31. }
  32.  
  33. function setMutationHandler(baseNode, selector, cb) {
  34. var ob = new MutationObserver(function(mutations){
  35. for (var i=0, ml=mutations.length, m; (i<ml) && (m=mutations[i]); i++)
  36. for (var j=0, nodes=m.addedNodes, nl=nodes.length, n; (j<nl) && (n=nodes[j]); j++)
  37. if (n.nodeType == 1)
  38. if ((n = n.matches(selector) ? [n] : n.querySelectorAll(selector)) && n.length)
  39. if (!cb(ob, n))
  40. return;
  41. });
  42. ob.observe(baseNode, {subtree:true, childList:true});
  43. }