Jump to content

User:Kxx/fix images.js

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Kxx (talk | contribs) at 08:36, 22 May 2024. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
(function(undefined) {
    const srcRegex = /^((?:https?:)?\/\/upload\.wikimedia\.org\/.*)\/thumb(\/.*\/)(\d{14}%21|)(.*)\/(\d+)px-\4(.*)$/;
    let imgs = document.getElementsByTagName('img');
    for (let img of imgs) {
        let matches = srcRegex.exec(img.getAttribute('src'));
        if (!matches)
            continue;
        if (matches[4].substr(-4).toLowerCase() === '.svg' && matches[6] === '.png') {
            let obj = document.createElement('object');
            obj.type = 'image/svg+xml';
            obj.height = img.height;
            obj.width = img.width;
            obj.data = matches[1] + matches[2] + matches[3] + matches[4];
            obj.style = 'vertical-align: middle';
            img.parentNode.replaceChild(obj, img);
        } else if (matches[6] === '' && devicePixelRatio !== 1) {
            img.height = img.height;
            img.width = img.width;
            img.src = matches[1] + '/thumb' + matches[2] + matches[3] + matches[4] + '/' + Math.round(img.width * devicePixelRatio) + 'px-' + matches[4];
            img.onerror = (function(matches) {
                this.src = matches[1] + matches[2] + matches[3] + matches[4];
                this.removeAttribute('onerror');
            }).bind(img, matches);
        }
        img.removeAttribute('srcset');
    }
})();