Last active
January 11, 2022 09:54
-
-
Save AntonLitvin/b4839d5e864398499bd53da0f7192ace to your computer and use it in GitHub Desktop.
Разные полезные сниппеты
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lasy load | |
img.js-lazyload { | |
visibility: hidden; | |
} | |
img.js-lazyload.lazyloaded { | |
visibility: visible; | |
} | |
const options = { | |
root: null, | |
rootMargin: '0px', | |
threshold: 0.05 | |
}; | |
const lazyload = function(entries, observer) { | |
entries.forEach(function(entry) { | |
const target = entry.target; | |
const dataset = target.dataset; | |
if (entry.isIntersecting) { | |
try { | |
if ('src' in dataset) { | |
target.src = dataset.src; | |
} | |
if ('bg' in dataset) { | |
target.style.backgroundImage = `url(${dataset.bg})`; | |
} | |
target.classList.add('lazyloaded'); | |
observer.unobserve(target); | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
}); | |
}; | |
const observer = new IntersectionObserver(lazyload, options); | |
document.querySelectorAll('.js-lazyload').forEach(elem => observer.observe(elem)); | |
<!-- Изображение без плейсхолдера --> | |
<img class="js-lazyload" data-src="path/to/image/elephant.jpg" alt="The pink elephant"> | |
<!-- Изображение с плейсхолдером --> | |
<img class="js-lazyload" data-src="path/to/image/elephant.jpg" src="path/to/placeholder.jpg" alt="The pink elephant"> | |
<!-- Ситуация, когда изображение надо задать как фон --> | |
<div class="js-lazyload" data-bg="path/to/image/elephant.jpg"></div> | |
======================================== | |
// Откоючить ховер при скролле | |
.disable-hover { | |
pointer-events: none; | |
} | |
let timer; | |
window.addEventListener('scroll', () => { | |
clearTimeout(timer); | |
if (!document.body.classList.contains('disable-hover')) { | |
document.body.classList.add('disable-hover') | |
} | |
timer = setTimeout(() => { | |
body.classList.remove('disable-hover') | |
}, 500); | |
}, false); | |
======================================= | |
// overflow: hidden для Safari | |
//html, body: width: 100%; | |
// 1. Фиксация <body> | |
function bodyFixPosition() { | |
setTimeout( function() { | |
/* Ставим необходимую задержку, чтобы не было «конфликта» в случае, если функция фиксации вызывается сразу после расфиксации (расфиксация отменяет действия расфиксации из-за одновременного действия) */ | |
if ( !document.body.hasAttribute('data-body-scroll-fix') ) { | |
// Получаем позицию прокрутки | |
let scrollPosition = window.pageYOffset || document.documentElement.scrollTop; | |
// Ставим нужные стили | |
document.body.setAttribute('data-body-scroll-fix', scrollPosition); // Cтавим атрибут со значением прокрутки | |
document.body.style.overflow = 'hidden'; | |
document.body.style.position = 'fixed'; | |
document.body.style.top = '-' + scrollPosition + 'px'; | |
document.body.style.left = '0'; | |
document.body.style.width = '100%'; | |
} | |
}, 15 ); /* Можно задержку ещё меньше, но у меня работало хорошо именно с этим значением на всех устройствах и браузерах */ | |
} | |
// 2. Расфиксация <body> | |
function bodyUnfixPosition() { | |
if ( document.body.hasAttribute('data-body-scroll-fix') ) { | |
// Получаем позицию прокрутки из атрибута | |
let scrollPosition = document.body.getAttribute('data-body-scroll-fix'); | |
// Удаляем атрибут | |
document.body.removeAttribute('data-body-scroll-fix'); | |
// Удаляем ненужные стили | |
document.body.style.overflow = ''; | |
document.body.style.position = ''; | |
document.body.style.top = ''; | |
document.body.style.left = ''; | |
document.body.style.width = ''; | |
// Прокручиваем страницу на полученное из атрибута значение | |
window.scroll(0, scrollPosition); | |
} | |
} | |
// отложенная загрузка блокирующих скриптов | |
var fired = false; | |
window.addEventListener('scroll', () => { | |
if (fired === false) { | |
fired = true; | |
setTimeout(() => { | |
// Здесь все эти тормознутые трекеры, чаты и прочая ересь, | |
// без которой жить не может отдел маркетинга, и которые | |
// дико бесят разработчиков, когда тот же маркетинг приходит | |
// с вопросом "почему сайт медленно грузится, нам гугл сказал" | |
}, 1000) | |
} | |
}); | |
// еще вариант | |
<script> | |
window.onReadyState = (e, t) => { | |
const a = ["loading", "interactive", "complete"], | |
o = a.slice(a.indexOf(e)), | |
n = () => o.includes(document.readyState); | |
n() ? t() : document.addEventListener("readystatechange", (() => n() && t())); | |
} | |
window.onReadyState("complete", function(){ | |
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)}; | |
m[i].l=1*new Date(); | |
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a) | |
}) (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym"); | |
ym(57194593, "init", { clickmap:true, trackLinks:true, accurateTrackBounce:true, webvisor:true }); | |
</script> | |
<noscript><div><img src="https://mc.yandex.ru/watch/57194593" style="position:absolute; left:-9999px;" alt="" /></div></noscript> | |
// Регулярка, меняющая тег img на picture, с ограничениями по пути до картинки | |
document.querySelectorAll('img').forEach(n => { | |
const src = n.getAttribute('src'); | |
if (!/^https?:\/\//.test(src)) { | |
const picture = document.createElement('picture'); | |
picture.innerHTML = `<source srcset="${src}" type="image/svg+xml">${n.outerHTML}`; | |
n.parentElement.replaceChild(picture, n); | |
} | |
}); | |
// Отработка в зависимости от положения наведения, например для выпадающего меню | |
const test = document.querySelector('.test'); | |
test.addEventListener('mouseover', function(e) { | |
if(e.clientX < test.clientWidth/2){ | |
alert('право, бл@@@'); | |
}else{ | |
alert('лево, бл@@@'); | |
} | |
}, false); | |
// Как разделить элементы меню на 2 части логотипом | |
$(function(){ | |
var navElements = $('.nav > li'), | |
navElementsLength = $(navElements).length, | |
middle = navElementsLength / 2, | |
middle = Math.round(middle); | |
$(navElements).eq(middle-1).addClass('left'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment