How can I inject a <script src="https://remote.com/"></script>
element into my page, wait for it to execute, and then use functions that it defines?
FYI: In my case, the script will do some credit card processing in rare cases, so I don't want to include it always. I want to include it quickly when the user opens up a change-credit-card-options dialog, and then send it the new credit card options.
Edit for additional detail: I do not have access to the remote script.
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.
The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.
The “script” tag JavaScript programs can be inserted almost anywhere into an HTML document using the <script> tag. You can run the example by clicking the “Play” button in the right-top corner of the box above. The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag.
Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
You could use Google Analytics or Facebook's method:
(function(d, script) { script = d.createElement('script'); script.type = 'text/javascript'; script.async = true; script.onload = function(){ // remote script has loaded }; script.src = 'http://www.google-analytics.com/ga.js'; d.getElementsByTagName('head')[0].appendChild(script); }(document));
UPDATE:
Below is the new Facebook method; it relies on an existing script tag instead of <head>
:
(function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)){ return; } js = d.createElement(s); js.id = id; js.onload = function(){ // remote script has loaded }; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));
facebook-jssdk
with your unique script identifier to avoid it being appended more than once.Same method using event listeners and ES2015 constructs:
function injectScript(src) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; script.addEventListener('load', resolve); script.addEventListener('error', e => reject(e.error)); document.head.appendChild(script); }); } injectScript('https://example.com/script.js') .then(() => { console.log('Script loaded!'); }).catch(error => { console.error(error); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With