I have a simple script that I placed inside it's own file (my_file.js). This script depends on jQuery. Obviously users can access its functionality via the script tags inside the head tags:
<head>
<script src='http://code.jquery.com/jquery-3.3.1.min.js'></script>
<script src='my_file.js'></script>
</head>
This works perfectly, since the JS is loaded sequentially. But I would like users to not have to add jQuery explicitly at the top. Is there a way my_file.js can itself load jQuery prior to its own JS, such that users only add the one file:
<head>
<script src='my_file.js'></script>
</head>
I know modules and bundlers take care of this issue, but I'm interested to see if there is an approach that allows one file to bring in its dependency, and wait until it's loaded before running the rest of the script.
Is there something like dynamic imports, such that:
import('http://code.jquery.com/jquery-3.3.1.min.js').then(module => {
// load my scripts here
});
Or AJAX in vanilla JS:
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://code.jquery.com/jquery-3.3.1.min.js')
xhr.onload = function() {
if (xhr.status === 200) {
// load my scripts here
}
else {
console.log('Request failed. Returned status of ' + xhr.status)
}
}
Everything I try runs my_file.js before jQuery. How can I make sure jQuery is loaded first, without having to place it in the tags?