views:

100

answers:

3

Hi,

I need to dynamically add a script reference, so I do this:

jQuery('html head').append("<script src='somesource.com/somejs.js'><\/script>")

and it does't work - I don't get any errors but I can't execute any of the methods defined inside that script.

Any ideas what I am doing wrong?

Thanks! Andrey

A: 

You need a type='text/javascript':

jQuery('html head').append("<script type='text/javascript' src='somesource.com/somejs.js'><\/script>")
mahemoff
While this is technically true (in HTML 4.x and XHTML 1.x), browsers error recover, so this isn't the cause of the fault.
David Dorward
None of modern browsers I tested cares about specifying script type.
Andrey
+1  A: 

Without seeing the script in context, it is hard to say, but possibilities include:

  1. You have the URL wrong (you have what appears to be a domain name, but no protocol in the URI)
  2. You are trying to use the functions without allowing time for the browser to download and run the script (so they aren't defined at the time you call them)
David Dorward
You have nailed one of the problems - browser doesn't have enough time to download script before I call a method from that script.
Andrey
+5  A: 

jQuery has a getScript method:

$(document).ready(function() {
  $.getScript('somesource.com/somejs.js');
});
FinnNk
$.getScript does pretty much what I was doing in my question, but in a shorter statement, hence you get a point :)
Andrey