jQuery / JS在文档准备好之前加载内容

I'm searching for a solution (jQuery or plain JS) that allows loading HTML/JS-Content into a given DIV before(!) DOM is loaded completely.

<script>
$(document).ready(function() {
var mywidth = $(window).width();
if(mywidth > 1000) {
$("#mydiv").load("some_html_with_external_javascript.html");
}
});

This works fine - of course. But if the loaded content contains external JS, the JS-Content is not executed. I need something like a mix of JS and PHP, something like:

<div id="mydiv">
<script>
var mywidth = $(window).width();
if(mywidth > 1000) {
// <?php require_once "some_html_with_external_javascript.html"; ?>
}
</script>
</div>

You can use document.write in order to do that. Just insert a new script tag at the current position, which is executed before the next (script) tags (very similar to the php code). According to your question, the requested script is loaded synchronously.

index.html:

<script>
console.log("first")
document.write('<script src="second.js"><\/script>')
</script>
<script>
console.log("third")
</script>

second.js:

console.log("second")

The browser console will load second.js first before logging "third". The output is therefore, as expected:

  • "first"
  • "second"
  • "third"

I want to add that synchronous loading should be avoided, if possible. This is a huge performance bottleneck.