Reputation: 109
I'm trying to 'include' some generated HTML code on my page with jQuery load (injecting it into #loadhead div):
<script>
$("#loadhead").load("head.php");
</script>
<script defer>
... rest of the code
</script>
I want the second part of the script to load only after head.php is done loading. I tried to enforce execution of the second script tag with defer, but it deson't seem to work - still, once in a while, head.php doesn't manage to load before the rest of the code. What can I do to ensure it is always loaded completely? It generates some JavaScript values that are used by the 'defer' script.
Upvotes: 0
Views: 313
Reputation: 1073988
Two options for you:
load
's callbackPut your second script's code in a function, so it's loaded but not run, and then call that function from load
's success callback.
Example:
<script>
$("#loadhead").load("head.php", otherStuff);
function otherStuff() {
// ...
}
</script>
(I didn't see any reason they should be in separate script
tags, so they aren't.)
I'd probably put that all in a .js
file and link it rather than having script embedded in the HTML inline.
load
is doneDon't include the second script
tag at all; load the script later in the load
success callback, either using $.getScript
or appending a script
element.
Example:
<script>
$("#loadhead").load("head.php", function() {
$.getScript("otherstuff.js");
});
</script>
(I didn't see any reason they should be in separate script
tags, so they aren't.)
I'd very much go with Option #1, to avoid unnecessary delays.
Upvotes: 2