The following function will assist you in dynamically including JavaScript files. :
1 2 3 4 5 6 7 8 9 10 11 12 | function dynamic_js_includer(script_link, script_id='my_js_script') { if (!document.getElementById(script_id)) { let boot = document.createElement('script'); boot.src = script_link; //boot.setAttribute('type', 'module'); boot.setAttribute('id', script_id); boot.onload = e => { //any action after script is loaded }; document.body.appendChild(boot); } } |
Such inclusion enables loading only the necessary functionality on a page, avoiding the inclusion of numerous JS files that can slow down page loading.
script_id: allows to avoid of including the same file more than one time
