In my page body, I need to insert this code as the result of an AJAX call:
Loading jQuery
It is pretty safe. Historically, <script>
tags are full blocking, hence the second <script>
tag can't get encountered befored the former has finished parsing/excuting. Only problem might be that "modern" browsers tend to load scripts asynchronously and deferred. So to make sure order is correct, use it like this:
<p>Loading jQuery</p>
<script type='text/javascript' async=false defer=false src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
$.ajax({
...
});
</script>
However, it's probably a better idea it use dynamic script tag insertion instead of pushing this as HTML string into the DOM. Would be the same story
var scr = document.createElement('script'),
head = document.head || document.getElementsByTagName('head')[0];
scr.src = 'scripts/jquery/core/jquery-1.4.4.js';
scr.async = false; // optionally
head.insertBefore(scr, head.firstChild);
Wait for multiple scripts to load
The following helper loads multiple scripts only once and returns a promise:
async function cirosantilli_load_scripts(script_urls) {
function load(script_url) {
return new Promise(function(resolve, reject) {
if (cirosantilli_load_scripts.loaded.has(script_url)) {
resolve();
} else {
var script = document.createElement('script');
script.onload = resolve;
script.src = script_url
document.head.appendChild(script);
}
});
}
var promises = [];
for (const script_url of script_urls) {
promises.push(load(script_url));
}
await Promise.all(promises);
for (const script_url of script_urls) {
cirosantilli_load_scripts.loaded.add(script_url);
}
}
load_scripts.loaded = new Set();
(async () => {
await cirosantilli_load_scripts([
'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js',
]);
// Now do stuff with those scripts.
})();
GitHub upstream: definition and usage.
Tested in Chromium 75.
const jsScript = document.createElement('script')
jsScript.src =
'https://coolJavascript.js'
document.body.appendChild(jsScript)
jsScript.addEventListener('load', () => {
doSomethingNow()
})
Will load after the script is dynamically added
$.ajax and $.load are the same thing. You can use either. If you put $.load in a script tag on the page it will fire when it loads just like $.ajax().
When it comes to waiting for a script to fire before you do something what Tomalak said is kinda true. The exception is asynchronous calls. Javascript will make an AJAX call then continue running the script and when the AJAX call responds it will run the success/fail depending on what you tell it to do.
Now say you want your JS to wait for the return, with a single call it's pretty easy just wrap every thing in the success callback, or you could do it the cool way and use $.deferred. This allows you to make a bunch of ajax calls or one and then run some code only after the finish.
$.when & $.then are probably the best for this situation.
Any way what your are doing is safe.
Add an ID to your script file so you can query it.
<script id="hljs" async src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.0.0/highlight.min.js"></script>
Then add a load listener to it in JavaScript
<script>
var script = document.querySelector('#hljs');
script.addEventListener('load', function() {
hljs.initHighlightingOnLoad();
});
</script>
There is also new feature in jQuery 1.6
. It is called jQuery.holdReady()
. It is actually self explanatory; when you call jQuery.holdReady(true)
, ready
event is not fired until you call jQuery.holdReady(false)
. Setting this to false will not automatically fire a ready event, it just removes the hold.
Here is a non-blocking example of loading a script taken from the documentation:
$.holdReady(true);
$.getScript("myplugin.js", function() {
$.holdReady(false);
});
See http://api.jquery.com/jQuery.holdReady/ for more information