Skip to content

Instantly share code, notes, and snippets.

@AndrewSavetchuk
Last active March 19, 2024 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewSavetchuk/612479aeef35a9d4ea43135d283782a1 to your computer and use it in GitHub Desktop.
Save AndrewSavetchuk/612479aeef35a9d4ea43135d283782a1 to your computer and use it in GitHub Desktop.

Execute Code When the Document Loading Has Finished

This is a common pattern used to ensure that code runs after the DOM has fully loaded, which can be important for accessing and manipulating elements on the page without encountering errors related to the DOM not being fully constructed.

function ready(fn) {
  if (document.readyState === "loading") {
    // Loading hasn't finished yet
    document.addEventListener("DOMContentLoaded", fn);
  } else {
    // `DOMContentLoaded` has already fired
    fn();
  }
}

Insert Script Tag(s) into HTML

This function will insert the script tags into the <head></head>.

Scripts marked as defer are executed after the DOM parsing is complete in the order in which they are defined in the markup. If you need to load the scripts immidiately (after inserting), remove this line: script.defer = true.

However, you should be careful when placing your scripts into the <head></head> without async or defer.

function insertScript(src) {
    const script = document.createElement('script');
    script.src = src;
    script.async = false;
    script.defer = true;
    document.head.appendChild(script);
}

addScript('1.js'); // 1. This script will start loading immediately.
addScript('2.js'); // 2. This script will be executed as soon as the first one is loaded.
addScript('3.js'); // 3. This is guaranteed to be in order 1 -> 2 -> 3.

Detect the Mobile Operating System

function getMobileOperatingSystem() {
    const ua = navigator.userAgent || navigator.vendor || window.opera;

    // Windows Phone must come first because its UA also contains "Android"
    if (/windows phone/i.test(ua)) {
        return "Windows Phone";
    }

    if (/android/i.test(ua)) {
        return "Android";
    }

    // iOS detection from: http://stackoverflow.com/a/9039885/177710
    if (/iPad|iPhone|iPod/.test(ua) && !window.MSStream) {
        return "iOS";
    }

    return "unknown";
}

Disabled Drag for Images and Links (jQuery)

The example below is deprecated, the function is here for historical purposes.

Nowadays, we can now use the CSS property user-drag: none;

function disableDrag() {
    $("img, a").on("dragstart", function(event) {
       event.preventDefault();
    });
}

Replace Cyrillic characters with Latin characters

function replaceCyrillic(str) {
    let output = str;

    const cyr = [
        'а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п',
        'р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я',
        'А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П',
        'Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я',
    ];

    const lat = [
        'a','b','v','g','d','e','io','zh','z','i','y','k','l','m','n','o','p',
        'r','s','t','u','f','h','ts','ch','sh','sht','a','i','y','e','yu','ya',
        'A','B','V','G','D','E','Io','Zh','Z','I','Y','K','L','M','N','O','P',
        'R','S','T','U','F','H','Ts','Ch','Sh','Sht','A','I','Y','e','Yu','Ya',
    ];
    
    
    for (let j = 0; j < cyr.length; j++) {
        output = output.replace(cyr[j], lat[j]);
    }
    
    return output;
}

console.log(replaceCyrillic('Тестовая строка')); // => 'Testovaya стrоkа'

Handle the Click Event on Dynamically Created Elements (jQuery)

In the example below, the .class element is a dynamically created element.

$('body').on('click', '.class', function() {
    // do something
});

Force Viewport Width if Device Width Is Less Than N (jQuery)

function forceViewportSize() {
    var viewport = $('meta[name="viewport"]');
    
    if (screen.availWidth < 480) {
        viewport.attr("content", "width=320, user-scalable=no");
    } else {
        viewport.attr("content", "width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no");
    }
}

$(document).ready(function() {
    forceViewportSize();
});

$(window).on('resize', function() {
    forceViewportSize();
});

$(window).on("orientationchange", function() {
    forceViewportSize();
});

Fire a Callback When the Image Is Loaded (jQuery)

$('img').each(function() {
    const img = new Image();
    
    img.onload = function() {
        console.log($(this).attr('src') + ' - loaded!');
    }
    
    img.src = $(this).attr('data-src'); // This can be used for lazy-loading
});

Check if the Browser Is Internet Explorer (Outdated)

Fortunately, we don't need to do this anymore, the function is here for historical purposes.

function isIE() {
    const ua = navigator.userAgent.toLowerCase();
    return ua.indexOf('msie') !== -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment