0

I have my scripts.js file.

If I'd like to insert an external resoruce (like the swfobject.js library from youtube) inside this file how can I do it?

Like :

<script type="text/javascript" src="swfobject.js"></script>   

Is it possible? Maybe with less code with jQuery...

markzzz
  • 47,390
  • 120
  • 299
  • 507

5 Answers5

2

You can use the getscript api of jQuery

$.getScript('swfobject.js', function(data, textStatus){ })

jQuery.getscript()

LoneWOLFs
  • 2,306
  • 3
  • 20
  • 38
1

Please see:

http://jqfundamentals.com/#example-1.2

Well it seems you already know the best way to do this.

mohsensajjadi
  • 325
  • 1
  • 6
  • 18
1

Here is an example code of simple dynamic loader which loads several scripts in serial manner:

https://github.com/miohtama/Krusovice/blob/master/src/krootstrap.js

  • First detect the base URL of the current script file (loader) if you are using relative URLs. This needs some magic, because Javascript does not know its own location. If you have full HTTP URL to the file then you can skrip this test

  • Inject new tag to using DOM manipulation

  • Follow the script loading process and call a callback function when done (note that you cannot call any functions inside JS until it is loaded, thus you need to wait this callback)

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • What's behind the magic :) You need to be careful about the serial thing if you are loading several scripts - jQuery.getScript() doesn't do it for you. – Mikko Ohtamaa Sep 06 '11 at 10:12
1

The simplest you can do is something like this:

function importScript(path) {
    var el = document.createElement('script');
    el.type = 'text/javascript';
    el.src = path;
    var parent = document.getElementsByTagName('head')[0];
    if(!parent) parent = document.body;
    parent.appendChild(el);
}

Actually, it could be simpler still if you're sure the head always exists, of if you decide to always attach the script to the document body anyway.

bart
  • 7,640
  • 3
  • 33
  • 40
0

There are many ways to load scripts dynamically, but what I think you want is something as simple as this:

function importScript(path) {
  document.write('<script type="text/javascript" src="' + path + '"></scr' + 'ipt>');
}

importScript('/scripts/jquery-1.6.2.min.js');
Infeligo
  • 11,715
  • 8
  • 38
  • 50