How to load the JS dynamically
-
I want to delay loading all scripts and styles until there is user interaction on the form. Is this possible, and what is the proper way to do it?
I’ve tried this approach – using a template wrapper, loading the scripts that are loaded if enqueued properly, and although they get appended properly, the form just refershed the page when submitted:<template id="cf7-scripts-template"> <script src="/wp-content/plugins/contact-form-7/includes/swv/js/index.js?ver=5.9.2" id="swv-js"></script> <script id="contact-form-7-js-extra"> var wpcf7 = {"api":{"root":"https:\/\/\/wp-json\/","namespace":"contact-form-7\/v1"}}; </script> <script src="https:///wp-content/plugins/contact-form-7/includes/js/index.js?ver=5.9.2" id="contact-form-7-js"></script> </template> document.addEventListener('DOMContentLoaded', function() { // Flag to track if Contact Form 7 scripts have been outputted var cf7ScriptsOutputted = false; // Function to output Contact Form 7 scripts and fetch schema function outputContactForm7ScriptsAndFetchSchema() { if (!cf7ScriptsOutputted) { var template = document.getElementById('cf7-scripts-template'); var clone = document.importNode(template.content, true); document.body.appendChild(clone); cf7ScriptsOutputted = true; // Fetch Contact Form 7 schema fetch('https://framework.pwdev.co.uk/wp-json/contact-form-7/v1/contact-forms/97/feedback/schema') .then(response => response.json()) .then(data => { // Process the schema data as needed console.log('Contact Form 7 Schema:', data); }) .catch(error => { console.error('Error fetching Contact Form 7 schema:', error); }); wpcf7.reset( form ); } } // Hook into input field events var formInputs = document.querySelectorAll('.wpcf7-form-control'); formInputs.forEach(function(input) { input.addEventListener('input', function() { // Output additional Contact Form 7 scripts and fetch schema when user starts typing outputContactForm7ScriptsAndFetchSchema(); }); }); });
- The topic ‘How to load the JS dynamically’ is closed to new replies.