I have a dynamic web page where I need to import an external JS file (under an IF
condition) inside another javascript file.
I tried to search for a feasible solution but it didn't work.
I have tried loading a JS file to the DOM using document.createElement()
but it also didn't work. Apparently the Js was loaded into the DOM but was not accessible in the current JS file.
Solution in jQuery will also be fine
Dynamic loadingThose files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.
Locate the correct Javascript download of the library you want to install. Download the library and make a copy in your sketch folder. (If you're using the web editor, you can upload the relevant files using Upload file in the dropdown in the “Sketch Files” sidebar.) Add a <script> tag to your sketch's index.
My guess is that in your DOM-only solution you did something like:
var script = document.createElement('script');
script.src = something;
//do stuff with the script
First of all, that won't work because the script is not added to the document tree, so it won't be loaded. Furthermore, even when you do, execution of javascript continues while the other script is loading, so its content will not be available to you until that script is fully loaded.
You can listen to the script's load
event, and do things with the results as you would. So:
var script = document.createElement('script');
script.onload = function () {
//do stuff with the script
};
script.src = something;
document.head.appendChild(script); //or something of the likes
jQuery's $.getScript()
is buggy sometimes, so I use my own implementation of it like:
jQuery.loadScript = function (url, callback) {
jQuery.ajax({
url: url,
dataType: 'script',
success: callback,
async: true
});
}
and use it like:
if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
//Stuff to do after someScript has 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