In Web front-end development (http://www.maiziedu.com/course/web-px/) , we may need to use JQuery Loading an external CSS file or js file, loading external files in a variety of ways, the following specific look at the various loading methods
JS mode to load CSS, JS files:
Load CSS file function includecss (filename) {
var head = document.getElementsByTagName (' head ') [0];
var link = document.createelement (' link ');
Link.href = filename;
Link.rel = ' stylesheet ';
Link.type = ' text/css ';
Head.appendchild (link)}
Load JS file function Includejs (filename) {
var head = document.getElementsByTagName (' head ') [0];
var script = document.createelement (' script ');
SCRIPT.SRC = filename;
Script.type = ' Text/javascript ';
Head.appendchild (script)}
The above way is very simple, but there will be some problems, such as the loading JS file, you need to execute the method of JS, this time occasionally can not find the method to execute, because the possibility of loading JS file, the network card dropped, so you need to load in a different way, using JQuery to load CSS files:
$ ("Head"). Append ("<link>"); var css = $ ("head"). Children (": Last"); Css.attr ({
Rel: "Stylesheet",
Type: "Text/css",
HREF: "Address_of_your_css"});
Jquery loads JS files in two ways:
$.ajax ({
URL: "JS file",
DataType: "Script",
Cache:true,
Success:function () {
Todo
}});
$.getscript (' JS file ', function () {
TODO});
Both of the above can be, and both after loading the JS file, and then execute the JS Internal method (there is no way to find the method execution error), the second will be simpler.
So what if we need to load multiple JS files?
$.when (
$.getscript ("/mypath/myscript1.js"),
$.getscript ("/mypath/myscript2.js"),
$.getscript ("/mypath/myscript3.js"),
$. Deferred (function (Deferred) {
$ (deferred.resolve);
})
). Done (function () {
Place your code here, the scripts is all Loaded});
If multiple calls are required, you can also draw out the method:
Define $.getmultiscripts = function (arr, path) {
var _arr = $.map (arr, function (SCR) {
Return $.getscript ((path| | ") + SCR);
});
_arr.push ($. Deferred (function (Deferred) {
$ (deferred.resolve);
}));
Return $.when.apply ($, _arr);}
Call var Script_arr = [
' Myscript1.js ',
' Myscript2.js ',
' Myscript3.js '
];$.getmultiscripts (Script_arr, '/mypath/'). Done (function () {
All scripts Loaded});
The above on the jquery loading JS files, CSS file several methods, you can choose according to their own preferences. Hope to help everyone.
What are the methods for JQuery to load CSS and JS files?