Injecting Local JavaScript and CSS from the Console
Published on June 18, 2020
When testing JavaScript and CSS changes locally, especially on live or staging environments, it’s sometimes helpful to load files directly from the browser console without modifying the site’s source code. I use the following snippets to quickly inject local or external .js and .css files into a webpage during development. This blog entry serves as a personal reference for easy copy-paste access. May come in handy for others doing quick frontend testing or debugging.
Load CSS from console
Loading local css file as link element.
// Create empty link element
var link_element = document.createElement("link");
// Define css file path
var css_path = "[path_to_css_file]"
// Define attributes for link element
link_element.setAttribute("rel","stylesheet");
link_element.setAttribute("href",css_path);
document.head.appendChild(link_element);
Load JS from console
Loading local js file as script element.
// Create empty script element
var script_element = document.createElement("script");
// Define js file path
var js_path = "[path_to_js_file]"
// Define attributes for script element
script_element.setAttribute("src",js_path);
script_element.setAttribute("type","text/javascript");
document.head.appendChild(script_element);