From 3d5c68dd7c9f05f913fe225486437bc95f282305 Mon Sep 17 00:00:00 2001 From: Bill Randall Date: Thu, 7 Mar 2024 15:50:35 -0500 Subject: [PATCH] Use a combined promise to ensure the scripts are loaded before running the real script, which depends on these script imports --- public/campaign-form.js | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/public/campaign-form.js b/public/campaign-form.js index 528c3cd..c6de19b 100644 --- a/public/campaign-form.js +++ b/public/campaign-form.js @@ -1,7 +1,4 @@ -var script = document.createElement('script'); -var script2 = document.createElement('script'); -var script3 = document.createElement('script'); -script3.onload = function () { +const postScriptLoad = function () { // Only initialize campaign-forms JS if it hasn't loaded previously. if (typeof window.campaignForms === 'undefined') { @@ -183,10 +180,33 @@ script3.onload = function () { })(jQuery) } }; -script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js' -script2.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js' -script3.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js' -document.head.appendChild(script); -document.head.appendChild(script2); -document.head.appendChild(script3); +const createScriptTag = (info) => { + return new Promise(function(resolve, reject) { + let scriptElement = document.createElement('script'); + scriptElement.src = info; + scriptElement.async = false; + scriptElement.onload = () => { + resolve(info); + }; + scriptElement.onerror = () => { + reject(info); + }; + document.body.appendChild(scriptElement); + }); +}; + +const scripts = ['https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js', + 'https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js', + 'https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js']; + +let promiseData = []; +scripts.forEach((info) => { + promiseData.push(createScriptTag(info)); +}); + +Promise.all(promiseData).then(() => { + postScriptLoad(); +}).catch((data) => { + console.warn(data + ' failed to load!'); +});