When we need jquery in JavaScript and can't tell if it's loaded, you can automatically judge and load jquery in the following ways:
The code is as follows |
Copy Code |
function Getscript (URL, success) { var script = document.createelement (' script '); script.src = URL; var head = document.getElementsByTagName (' head ') [0], Done = false;
Attach handlers for all browsers Script.onload = Script.onreadystatechange = function () { if (!done && (!this.readystate | | | this.readystate = ' loaded ' | | | this.readystate = ' complete ')) { Done = true;
callback function provided as Param Success ();
Script.onload = Script.onreadystatechange = null; Head.removechild (script); }; }; Head.appendchild (script); }; if (typeof jQuery = = ' undefined ') { Alert (' Not found JQuery '); Getscript (' Http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js ', function () { Alert (' jQuery loaded '); }); } |
loadscript Asynchronous Load Script
First, the grammar:
Loadscript (Url[,callback])
Or
Loadscript (Settings)
Second, the settings supported parameters:
URL: Script Path
Async: Asynchronous, default false (HTML5)
CharSet: File Encoding
Cache: Caching, default to True
Success: A function that executes after the load succeeds, giving priority to executing the callback.
Third, the invocation example:
The code is as follows |
Copy Code |
Loadscript (Url[,callback]) Loadscript ("Http://code.jquery.com/jquery.js"); Loadscript ("Http://code.jquery.com/jquery.js", function () { Console.log (1) }); Loadscript (Settings) Loadscript ({"url": "Http://code.jquery.com/jquery.js", "async": false, "CharSet": "Utf-8〃," cache ": false}); Loadscript ({"url": "Http://code.jquery.com/jquery.js", "async": false, "CharSet": "Utf-8〃," Success ": function () { Console.log (2) }}); Or you can purple: Loadscript (Settings[,callback]) Loadscript ({"url": "Http://code.jquery.com/jquery.js", "async": false, "CharSet": "Utf-8〃},function () { Console.log ($) });
|
Four, the source code:
The code is as follows |
Copy Code |
function Loadscript (url,callback) { var head = Document.head | | document.getElementsByTagName ("Head") [0] | | Document.documentelement, Script Options if (typeof url = = = "Object") { options = URL; url = undefined; } s = Options | | {}; url = URL | | s.url; Callback = callback | | s.success; script = document.createelement ("script"); Script.async = S.async | | false; Script.type = "Text/javascript"; if (s.charset) { Script.charset = S.charset; } if (S.cache = = false) { URL = url+ (/?/.test (URL)? "&": "?" + "_=" + (new Date ()). GetTime (); } script.src = URL; Head.insertbefore (script, head.firstchild); if (callback) { Document.addeventlistener? Script.addeventlistener ("Load", callback, false): Script.onreadystatechange = function () { if (/loaded|complete/). Test (Script.readystate)) { Script.onreadystatechange = null callback () } } } } |