What is the most lightweight way to include the jQuery lib into a page dynamically? I'm working on a page where sometimes it runs a few custom scripts开发者_Go百科 (10 lines) and other times the entire jquery is also needed.
Just add a script tag for jQuery when you need it:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.example.com/jquery.js';
document.body.appendChild(script);
Just go ahead and include it.
If you have other pages where you use jQuery then it's probably already cached if they do much on your site (or visit it with any frequency). Use the minified form, though. The logic of using Google applies, but the likelihood of cache is smaller.
W.r.t your comments: How often do you validate the pages on your own site? If your site did get cracked, how soon would you know? If the Google-hosted code was altered, the speed of discovery would be many orders of magnitude higher, and the implications to your site would be relatively small, IMO.
Well once the user has already downloaded JQuery, it's cached on their system, so including it after the first initial download is really trivial. You might as well just include it on the pate that you need it on and not worry about trying to add it into the JS runtime later on during the page.
Include it from Google's CDN:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
There's a big chance your clients will already have jQuery cached in their browsers.
Yeah, I'd just include it always - its small, and if you use the google cdn it'll hopefully already be cached.
If you MUST load it on demand, you can write the code for appending a script tag to the body. This code is fairly common.
void((function(){
var e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.setAttribute('src','jquery.js');
document.body.appendChild(e)
})());
May be you'll find Google AJAX APIs usefull. You can call load jQuery whenever you need by calling:
google.load("jquery", "1");
<script src="http://www.google.com/jsapi"></script>
<script>
//your awesome google
google.load("jquery", "1");
</script>
i have no clue why these guys are saying that google is a security issue and they dont want google to serve it. yall are wrong (or give me reasons why) id say its more likely for you to download a bad or changed version of jquery (you should alwase go to the site) than google giving you issues. googles awesome and they make it easy, host if for you and prolly have more throughput than you weak webserver so why wouldnt you use it?
sorry for dup code im still getting started on this site but i cant find reply button
精彩评论