Forum Moderators: open
I use an external JavaScript service to show some widgets on my webpage:
<script type="text/javascript" src="http://www.externalsite.com/code.js"> </script>
But this server is very slow so it slows down my webpages load. I'd like to load this JS, but only when my webpages are already loaded.
Is it possible? Does a JavaScript load timeout?
That way the page will still display first, then load the script. The onload event won't fire until it's loaded though.
Alternately, you could have a little onload script on the page that inserts the <script> tag afterwards, that way the page will load, then the script will load afterwards.
and in later script, by delay or event, assign the source:
document.getElementById("externalid").src="http://www.externalsite.com/code.js";
I do have one major concern, though, regarding any off-site script. (I'm just being curious, here) Won't it run into the "same origin" restrictions?
Wouldn't it be easier to download the script from the external site and upload it to your own?
And yes, you might run into timeout. I haven't seen it with scripts, but I have seen it style sheets. Consider breaking the big script into smaller ones and load them one at a time, or have a "setinterval" that checks if the script has been loaded at intervals greater than the standard timeout (I think that's 30 seconds) that terminates once the scipt has been verified as loaded.
[edit/add] Didn't mean to imly the first response is bad. I'm just a slow typer. Okay?
[edited by: HOTmike at 5:26 pm (utc) on Nov. 1, 2007]
[mydomain.com...]
<script type="text/javascript" src="http://www.mydomain.com/load.js"></script>
<script id="externalid" type="text/javascript" src=""></script>
...
<body onload="loadExternalJs()">
[mydomain.com...]
function loadExternalJs()
{
document.getElementById("externalid").src = "http://www.externalsite.com/code.js";
}
This "code.js" makes some "document.getElementsByTagName" within my page. I don't know why it doesn't work.
function loadExternalJs()
{
var file="http://www.externalsite.com/code.js";
try{
if (document.createElement && document.getElementsByTagName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file);
head.appendChild(script);
}
}catch(err){}
}
Indicates that the script is not going to generate any document content. The browser can continue parsing and drawing the page
<script type="text/javascript" src="http://www.externalsite.com/code.js" defer="defer"> </script>