[英]jQuery/JS load content before document ready
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. 我正在寻找一种解决方案(jQuery或纯JS),该解决方案允许在完全加载DOM之前将HTML / JS内容加载到给定的DIV中。
<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.
但是,如果加载的内容包含外部JS,则不会执行JS-Content。 I need something like a mix of JS and PHP, something like:
我需要将JS和PHP混合在一起的东西,例如:
<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. 您可以使用document.write来做到这一点。 Just insert a new script tag at the current position, which is executed before the next (script) tags (very similar to the php code).
只需在当前位置插入一个新的脚本标签,该脚本标签将在下一个(脚本)标签之前执行(非常类似于php代码)。 According to your question, the requested script is loaded synchronously.
根据您的问题,请求的脚本被同步加载。
index.html: index.html:
<script>
console.log("first")
document.write('<script src="second.js"><\/script>')
</script>
<script>
console.log("third")
</script>
second.js: second.js:
console.log("second")
The browser console will load second.js first before logging "third". 浏览器控制台将在登录“ third”之前先加载second.js 。 The output is therefore, as expected:
因此,输出是预期的:
I want to add that synchronous loading should be avoided, if possible. 我想补充一点,如果可能的话,应该避免同步加载。 This is a huge performance bottleneck.
这是一个巨大的性能瓶颈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.