code • JavaScript tricks - martindubenet/wed-dev-design GitHub Wiki

JavaScript Basics  ][  JavaScript Tricks  ][  Vue.js & Vuetify  ]

JavaScript Tricks

 

Performance

When DOM is ready

Parameters to delay the execution of JavaScript declared within the head tag of an HTML document : sync difer

<head>
    <script src="" sync defer></script>
</head>

Or encapsulate the code within a function that gets loaded after, ounce the DOM is loaded.

function init() {
    const p = document.querySelector('p');
    console.log(p);
}
document.addEventListener('DOMContentLoaded', init);

 

UX

Smooth scrolling

This scrools to a particular set of coordinates within the document. (reference)

window.scrollTo({ top: 500, behavior: 'smooth' });

This YouTuber tutorial is more detailed on how to acheive a global smooth srolling experience with page anchors. He also shared his tutorial code in CodePen.

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

 

SEO

Google Tag Manager (GTM)

Create the DIV element dynamically to work around GTM

<script>
    var chatDiv = document.createElement('div');
    chatDiv.className = 'fb-customerchat';
    chatDiv.setAttribute('page_id', '1234567890123');
    document.body.appendChild(chatDiv);
</script>

 

Trustworthy JS Libraries

⚠️ **GitHub.com Fallback** ⚠️