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>

Print text strings in different formats

From PascalCase to kebab-case

Useful to convert a copy/pasted ReactJS file name as variable complient to CSS className in the DOM.

Gemini 2.5 Flash

function pascalToKebabCase(pascalCaseString: string): string {
  if (!pascalCaseString) {
    return '';
  }
  return pascalCaseString
    .replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2')
    .toLowerCase();
}

// Usage
console.log(pascalToKebabCase('LoremIpsum'));  // "lorem-ipsum"
console.log(pascalToKebabCase(''));            // ""
console.log(pascalToKebabCase('Example'));     // "example"

 

Trustworthy JS Libraries

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