1

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?

3 Answers 3

5

jQuery has a getScript method:

$(document).ready(function() {
  $.getScript('somesource.com/somejs.js');
});
Sign up to request clarification or add additional context in comments.

1 Comment

$.getScript does pretty much what I was doing in my question, but in a shorter statement, hence you get a point :)
1

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)

1 Comment

You have nailed one of the problems - browser doesn't have enough time to download script before I call a method from that script.
-2

You need a type='text/javascript':

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

2 Comments

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.
None of modern browsers I tested cares about specifying script type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.