Connecting Tech Pros Worldwide Forums | Help | Site Map

dynamically loading additional code from an url

20050407 prerelease
Guest
 
Posts: n/a
#1: Jul 24 '06
Hi!

Is it possible in a fairly portable manner to load additional javascript code
from a WWW URL? This would be useful for large-scale projects.


RobG
Guest
 
Posts: n/a
#2: Jul 24 '06

re: dynamically loading additional code from an url



20050407 prerelease posting ok wrote:
Quote:
Hi!
>
Is it possible in a fairly portable manner to load additional javascript code
from a WWW URL? This would be useful for large-scale projects.
<URL:http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/f39a6a56185a49c1/a4c3d5dcce0a08e6?tvc=1&q=document.createElement('s cript')&hl=en#a4c3d5dcce0a08e6>


Though maybe mini-fied code loaded once and cached may be a better
solution - it depends on your circumstance and users. There are a
number of JS minifiers out there:

<URL:http://www.google.com.au/search?q=minify+javascript&start=0>


--
Rob

Randy Webb
Guest
 
Posts: n/a
#3: Jul 24 '06

re: dynamically loading additional code from an url


20050407 prerelease posting ok said the following on 7/23/2006 9:01 PM:
Quote:
Hi!
>
Is it possible in a fairly portable manner to load additional javascript code
from a WWW URL? This would be useful for large-scale projects.
Yes, and although Rob gave you a URL to a thread that talks about how, I
am not sure it is the best, most comprehensive, thread to read about
dynamically creating JS files on the fly. Although it does give enough
to get started.

function loadJSFile(fileURL){
var newScript = document.createElement('script');
newScript.type = "text/javascript";
newScript.src = fileURL;
document.getElementsByTagName('head')[0].appendChild(newScript);
}

And call it as such:

loadJSFile('http://www.someDomain.com/someJSFile.js')

Beware that you may run into cross-domain security issues if you are
loading JS files from domains other than your own.

Also, if you are going to do a lot of loading, it may be worth the
benefit to appendChild to a div element and then clear it out so that
the script blocks don't keep piling up on you.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Closed Thread