Inside one of my views, I'd like to load this script:
<script type="text/javascript" src="https://domain.com" id="hello" name="abc"></script>
Is it possible to do that?
We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.
For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.
Manually appending it:
$('head').append('<script type="text/javascript" src="https://domain.com" id="hello" name="abc"></script>')
Using $.getScript
:
$.getScript('https://domain.com').done(function () {
// loaded!
});
RequireJS:
require.config({
paths: {
"myscript": "https://domain.com"
}
});
require(['myscript'], function () {
// loaded!
});
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