Adding a script reference into a page using jQuery
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?
jQuery has a getScript method:
$(document).ready(function() {
$.getScript('somesource.com/somejs.js');
});
Without seeing the script in context, it is hard to say, but possibilities include:
- You have the URL wrong (you have what appears to be a domain name, but no protocol in the URI)
- 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)
You need a type='text/javascript':
jQuery('html head').append("<script type='text/javascript' src='somesource.com/somejs.js'><\/script>")
精彩评论