Skip to content

Instantly share code, notes, and snippets.

@estelsmith
Last active February 3, 2020 19:54
Show Gist options
  • Save estelsmith/f800f168ebe39a2b155ab5ea6a6c7546 to your computer and use it in GitHub Desktop.
Save estelsmith/f800f168ebe39a2b155ab5ea6a6c7546 to your computer and use it in GitHub Desktop.
Helpful Code Snippets!
<?php
/**
* Plugin Name: CM Defer Inline JavaScript
* Description: Wraps all inline javascript to fire when document.readyState becomes interactive
*/
function cm_defer_js_script_wrapper()
{
$wrapper = <<<EOF
document.addEventListener('readystatechange', function () {
if (document.readyState === 'interactive') {
%s
}
});
EOF;
return $wrapper;
}
add_action('get_header', function () {
ob_start(function ($buffer) {
try {
$wrapper = cm_defer_js_script_wrapper();
$document = new DOMDocument();
$document->loadHTML($buffer);
$body = $document->getElementsByTagName('body')->item(0);
$scripts = $document->getElementsByTagName('script');
foreach ($scripts as $script) {
$src = $script->attributes->getNamedItem('src');
if ($src) continue;
$type = $script->attributes->getNamedItem('type');
if ($type && $type->value !== 'text/javascript') continue;
$script->nodeValue = sprintf($wrapper, $script->nodeValue);
}
return $document->saveHTML();
} catch (\Exception $e) {
return $buffer;
}
});
}, -100000);
// List all fonts that are being used on a page, along with the elements using them.
(function (document, getComputedStyle) {
console.clear();
let fontMap = {};
let elements = document.querySelectorAll('*');
elements.forEach(function (element) {
let computedStyles = getComputedStyle(element);
let fontFamily = computedStyles['font-family'];
if (!(fontFamily in fontMap)) {
fontMap[fontFamily] = new Array();
}
fontMap[fontFamily].push(element);
});
console.log(fontMap);
})(document, window.getComputedStyle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment