document.write is stalling the rest of my Javascript, solutions?
So my journey with this issue started when I initially was trying to asynchronously load a reddit social media widget. If you open the URL in the getScript
parameter below you'll notice that this does a direct 开发者_StackOverflowdocument.write
. If I didn't didn't capture that code, it would have rewritten the entire document when I run .getScript
.
var content = '';
document.write = function(s) {
content += s;
};
$.getScript('http://www.reddit.com/domain/skattertech.com/new/.embed?limit=4&t=all&sort=new&style=off', function(){
$('body').append(content);
});
The code above works, but despite the default async nature of .getScript
, pairing it up with document.write
causes my entire JS file to halt from running until it has the data to write. IF reddit's server is slow or doesn't respond, the rest of my other widgets won't load.
Is there any simple workarounds to solve this? Is it possible to fetch that script as a string to then split and pop the document.write
wrapper off? If the only thing left is the HTML, I can easy write that in at anytime without affecting the rest of my script right?
Sahas, with your clever trick of overriding the document.write function, I don't see any delay at all in executing the following script:
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
document.write = function(s) {
$("body").append(s);
};
$(function() {
$.getScript('http://www.reddit.com/domain/skattertech.com/new/.embed?limit=4&t=all&sort=new&style=off');
$("#testDiv").fadeIn('slow');
});
</script>
<style type="text/css">
#testDiv
{
background-color: #0c0c0c;
color: #fff;
display: none;
}
</style>
</head>
<body>
<p>This is a test</p>
<div id="testDiv">
<p>This is a test.</p>
<p>This div won't be shown until after $.getScript() executes.</p>
<p>Blah blah blah.</p>
</div>
</body>
I executed it several times and, even if reddit was slow to respond, my
$("#testDiv").fadeIn('slow');
code executed well before reddit was finished sending my page back the script.
Am I missing the problem?
精彩评论