Load Javascript Asynchronously
I have this java script that I insert into my sidebar. It is for a 350x200 ad banner.
<SCRIPT language="Javascript">
var cpmstar_rnd=Math.round(Math.random()*999999);
var cpmstar_pid=14214;
document.writeln("<SCR"+"IPT language='Javascript' src='http://server.cpmstar.com/view.aspx?poolid="+cpmstar_pid+"&script=1&rnd="+cpmstar_rnd+"'></SCR"+"IPT>");
</SCRIPT>
^ ^ This is the java script my ad network gave me, I cannot edit it
I want to load this ad banner as fast as possible without hindering the rest of my website.
Currently, what I do is I put开发者_高级运维 this ad tag on a blank html page, then I call that html page using an IFRAME on my sidebar. I heard that IFrames load asynchronously.
Is there any better method that I could use?
If your concern is practical rather than academic, go ahead and use an iframe. An iframe is essentially an embedded window, and as such does indeed load asynchronously.
You could also use Ajax to load the script, but the path of least resistance is to use an iframe (again, assuming you're more concerned with just getting it to work rather than ensuring your site validates -- if your doctype is XHTML Strict and you're serving your content as XML, you shouldn't use iframes, but I have a hunch you're not doing that).
start by updating your code
<script language="Javascript" type='text/javascript'>
var cpmstar_rnd=Math.round(Math.random()*999999);
var cpmstar_pid=14214;
document.writeln("<scr"+"ipt language='Javascript' src='http://server.cpmstar.com/view.aspx?poolid="+cpmstar_pid+"&script=1&rnd="+cpmstar_rnd+"'></scr"+"ipt>");
</script>
Iframes load asynchronously, but even if they didn't, embedding an untrusted external script in your page is a huge security hole, so it is good practice to use an iframe (if possible, one with a different domain) anyway.
Apart from that, an iframe might be slightly slower than asynchronous script loading via ajax due to the extra page request, but it is a lot simpler to maintain.
精彩评论