Skip to content

Instantly share code, notes, and snippets.

@jamischarles
Created April 16, 2024 18:51
Show Gist options
  • Save jamischarles/8eac2c5f628736b3ee8752b520ad97c6 to your computer and use it in GitHub Desktop.
Save jamischarles/8eac2c5f628736b3ee8752b520ad97c6 to your computer and use it in GitHub Desktop.
Inline JS into the dom. Careful. ensure you're running this through a build step of some sort to avoid browser errors
/**
* Stringifies a function, and wraps it in an IIFE so it'll auto execute.
* @remarks The assumption is that you'll be inlining this function into a vanilla \<script\> tag on the page.
* Therefore you should follow these rules:
* Standalone code. No imports / or deps on other files / methods.
* You can use TS, but carefully watch how the output is compiled down to ensure it works for the lowest browser target.
* Ensure safety. Anything that can fail should likely be wrapped in a try/catch.
* This will likely be used as blocking js. Keep it short!
* @param parameter1 - Allows passing a 1/2 string|number param to the function to be inlined.
* @param parameter2 - Allows passing a 2/2 string|number param to the function to be inlined.
*/
function inlineJS(
jsFunction, // TODO: type by function type you want to pass in?
parameter1?: number | string,
parameter2?: number | string,
) {
// if either param is a string, wrap in extra "" or quotes will be missing when fn is stringified and injected into script tag
if (typeof parameter1 === 'string') {
parameter1 = `"${parameter1}"`;
}
if (typeof parameter2 === 'string') {
parameter2 = `"${parameter2}"`;
}
// filter removes falsy values? Or just nullish ones?
const parameters = [parameter1, parameter2].filter(Boolean);
return `;(${jsFunction.toString()})(${parameters.join(',')});\n`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment