JS dynamic loading JS and CSS files

Source: Internet
Author: User

JS dynamic loading JS and CSS files

DEMO

An HTML page jsforjscss.html

1<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">2<Htmlxmlns= "Http://www.w3.org/1999/xhtml">3<Head>4<MetaHttp-equiv= "Content-type"Content= "text/html; Charset=utf-8 "/>5<ScriptType= "Text/javascript"Src= "Loadjscssfile.js"></Script> 6 <title> Untitled document </ Title> 7 </head> 8 <body> 9 </body>10 </< Span style= "color: #800000;" >html>           

Two dynamic loading JS file program Loadjscssfile.js

//JavaScript DocumentfunctionLoadjscssfile (Filename,filetype) {if (filetype = = "js"){var fileref = document.createelement (' script '); Fileref.setattribute ("type", "Text/javascript"); Fileref.setattribute ("src" ,filename);} else if (filetype = "css" var fileref = document.createelement (' link ' ); Fileref.setattribute ("rel", "stylesheet" ); Fileref.setattribute ("href" ,filename);} if (typeof fileref! = "undefined" ].appendchild (FileRef);}} Loadjscssfile ("Do.js", "JS"     

Three loaded JS files: do.js

Alert ("This was Do");

Four loaded CSS files: test.css (CSS file can also be used @import url ("Menu.css"); Introducing other CSS files)

@charset "Utf-8"; @import url ("Menu.css"); @import url (".. /gundong.css "); body{    background-color:Gray;} 


Theoretical analysis:

Rationale: The first step: using the DOM to create <script> or <link> tags, and give them attached properties, such as type, such as the second step: Using the AppendChild method to bind the label to another label, usually tied to the

Application: 1, improve the reuse of code, reduce the amount of code; 2, add a JavaScript controller and session can dynamically change the page style, 3, because the page is loaded from top to bottom of the file, and side loading side interpretation, So you can add JavaScript controller to control the loading order of the page file, such as loading CSS layout file, then displaying the CSS beautification file with the picture, then loading the large Falsh file, or the importance of the content of the security. R

Reading tip: E-text bad beginners can directly see the Chinese, and then copy the code under test. R

to load a. js or. css file dynamically, in a nutshell, it means using DOM methods to first create a swanky New "script" or "LINK" element, assign it the appropriate attributes, and finally, use Element.appendchild () to add the E Lement to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets See what it all comes together:

function loadjscssfile (filename, filetype) {
if (filetype== "JS") {//Decision file type
var fileref=document.createelement (' script ')//create Tag
Fileref.setattribute ("type", "Text/javascript")//The value of the definition property type is Text/javascript
Fileref.setattribute ("src", filename)//Address of File
}
else if (filetype== "CSS") {//Decision file type
var fileref=document.createelement ("link")
Fileref.setattribute ("rel", "stylesheet")
Fileref.setattribute ("type", "Text/css")
Fileref.setattribute ("href", filename)
}
if (typeof fileref!= "undefined")
document.getElementsByTagName ("Head") [0].appendchild (FileRef)
}



Loadjscssfile ("Myscript.js", "JS")//Open the page when the browser loads the file dynamically
Loadjscssfile ("javascript.php", "JS")//The browser dynamically loads "javascript.php" when the page is opened,
Loadjscssfile ("Mystyle.css", "CSS")//open page when the browser dynamically loads. css files

The next job is to bind to the

In this case, we can add a global array variable, the name of the binding file is stored inside, each time before binding check whether it already exists, if there is a hint already exists, if not exist on the binding. R

document.getElementsByTagName ("Head") [0].appendchild (FileRef)



by referencing the HEAD element of the page first and then calling AppendChild (), this means the newly cre ated element is added to the very end of the HEAD tag. Furthermore, you should was aware that no existing element was harmed in the adding of the new element-that are to say, if Y OU call Loadjscssfile ("Myscript.js", "JS") twice, your now end and the new "script" elements both pointing to the same Javascript file. This was problematic only from a efficiency standpoint, as you'll be adding redundant elements to the page and using Unnec Essary Browser Memory in the process. A simple-to-prevent the same file from being added more than once are to keep track of the files added by Loadjscssfile (), and only load a file if it ' s new:

By referencing the HEAD element of the page first and then calling AppendChild (), this means the newly-created element is Added to the very end of the HEAD tag. Furthermore, you should was aware that no existing element was harmed in the adding of the new element-that are to say, if Y OU call Loadjscssfile ("Myscript.js", "JS") twice, your now end and the new "script" elements both pointing to the same Javascript file. This was problematic only from a efficiency standpoint, as you'll be adding redundant elements to the page and using Unnec Essary Browser Memory in the process. A simple-to-prevent the same file from being added more than once are to keep track of the files added by Loadjscssfile (), and only load a file if it ' s new:



Here I ' m just crudely detecting to see if a file that's set to be added already exists within a list of added files ' names stored in variable filesadded before deciding whether to proceed or not.
Ok, moving on, sometimes the situation could require that's actually remove or replace an added. js or. css file. Lets See how that's done next.

JS dynamic loading JS and CSS files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.