From 8e11c17b186ab2d5dad1df0ac37cbbec6ef609f4 Mon Sep 17 00:00:00 2001 From: Moris Kramer Date: Sun, 16 Jul 2023 19:25:08 +0300 Subject: [PATCH] refactoring --- src/injectContentsquareScript.ts | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/src/injectContentsquareScript.ts b/src/injectContentsquareScript.ts index 6c241cb..cb6385a 100644 --- a/src/injectContentsquareScript.ts +++ b/src/injectContentsquareScript.ts @@ -4,31 +4,26 @@ type ScriptOptions = { /** * Appends the contentsquare script to document.head - * @param scriptOptions.clientId - the client id in the form of f6f72d509axzd - mandatory - * @param scriptOptions.defer - the script is fetched in parallel and evaluated after the document is parsed - defaults to false - * @param scriptOptions.async - the script is fetched in parallel and evaluated asap - defaults to true - * @param scriptOptions.integrity - the integrity hash of the contentsquare script - defaults to empty - * @returns the contentsquare script that was appended to document.head + * @param {ScriptOptions} scriptOptions - Options for injecting the script + * @param {string} scriptOptions.clientId - Client id, provided by Contentsquare.com (e.g.: 'a6f73d509') - Mandatory. + * @param {boolean} [scriptOptions.defer=false] - Script will be fetched in parallel with the HTML parsing, but execution will occur after the HTML document has been fully parsed. + * @param {boolean} [scriptOptions.async=true] - Script will be fetched in parallel with the HTML parsing, and it will be executed as soon as it is available, even if the HTML document is not fully parsed. + * @param {string} [scriptOptions.integrity] - Integrity hash (SRI) of Contentsquare script. Must be generated by Contentsquare. + * @returns {HTMLScriptElement} The contentsquare script that was appended to document.head */ -export function injectContentsquareScript(scriptOptions: ScriptOptions) { +export function injectContentsquareScript({ clientId, defer = false, async = true, integrity }: ScriptOptions) { const scriptElement = document.createElement("script"); scriptElement.type = "text/javascript"; + scriptElement.defer = defer; + scriptElement.async = async; - scriptElement.defer = - typeof scriptOptions.defer === "boolean" ? scriptOptions.defer : false; - - scriptElement.async = - typeof scriptOptions.async === "boolean" ? scriptOptions.async : true; - - if (scriptOptions.integrity) { - scriptElement.integrity = scriptOptions.integrity; + if (integrity) { + scriptElement.integrity = integrity; } scriptElement.crossOrigin = "anonymous"; - - scriptElement.src = - "https://t.contentsquare.net/uxa/" + scriptOptions.clientId + ".js"; + scriptElement.src = `https://t.contentsquare.net/uxa/${clientId}.js`; return document.head.appendChild(scriptElement); }