Tag Archives: ajax

How to load external scripts

0
Filed under JavaScript, Web Development
Tagged as , ,

Sometimes we, for some reason, need to load external scripts to be executed in our page. This post might help with some ideas about it.

There are, basically, two ways for loading scripts.

  1. Using a normal HTTP request
  2. Or using Ajax (XMLHttpRequest)

You can use both, depending on your needing. But what are the differences between them?

  1. Using a normal HTTP request, you append scripts from anywhere (cross-domain) which content is loaded only asynchronously.
  2. Using some Ajax, you can load text asynchronously or not, but you can’t get scripts from outside the domain/port you are (not normally, maybe the browser allow it, but not all browsers).

What’s the better? There’s no better. Just like always, it depends on what you are planning to do. So, are you trying to just execute a script? Or are you trying to get it and execute it so other code will be able to run? – It’s all about time. Loading the script sync/asynchronously makes the difference here.

So, if you need the script exaclty now, i mean, if the code must wait for the script, the solution is use sync Ajax. Otherwise, if the code can wait some milisseconds/secods (or it really doesn’t need to wait anything), you can use a normal HTTP request. Okay, but how?

Doing it using pure JavaScirpt is not that fun. It requires some code, and it can be annoying. So, let’s take a library (I’ll use utm here) to do the stuff). Take a look:

// loading the script asynchronously, normal HTTP request
u.append('script[type="text/javascript"][src="myscripts/some.js"]');
// we can add from another domain/port too:
u.append('script[type="text/javascript"][src="http://site.com/js/some.js"]');

The code above will basically simulate a simple script tag on the BODY of your document (yes, the BODY element is the best place to put scripts in. Why?)
In the other hand:

// I'll need a function called "show", that is in another script in my own domain.
var script = u.append('script[type="text/javascript"]');
// the 'true' here says it to do the request synchronously
script.text( u.get('myscripts/some.js', true) );

// now we can proceed. =)
show(...);

Choose which is better for what you need to do. ;)