JS dynamic loading of JS and CSS files

Source: Internet
Author: User

Jsforjscss.html

1 <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <HTML xmlns = "http://www.w3.org/1999/xhtml"> 3 

2. loadjscssfile. js

// JavaScript Documentfunction loadjscssfile(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("type","text/css");        fileref.setAttribute("href",filename);    }   if(typeof fileref != "undefined"){        document.getElementsByTagName("head")[0].appendChild(fileref);    }    }loadjscssfile("do.js","js");loadjscssfile("test.css","css");

3. Loaded JS file: Do. js

alert("this is do");

Iv. Loaded CSS file: test.css (you can also use @ import URL ("menu.css") in the CSS file to import other CSS files)

@charset "utf-8";@import url("menu.css");@import url("../gundong.css");body{    background-color:gray;}

Theoretical analysis:

Principle Analysis: Step 1: Use Dom to create <SCRIPT> or <link> tags and add attributes to them, such as type. Step 2: bind the tag to another tag using the appendchild method, it is usually bound to

Applications: 1. Improve code reuse and reduce the amount of code; 2. Add a javascript controller and session to dynamically change the page style; 3. Because the pages are loaded from top to bottom and explained while loading, you can add a javascript controller to control the loading sequence of page files, such as loading CSS layout files first, the CSS beautifying file with images is displayed, and a large falsh file is loaded, or the importance of security content is loaded. R

Reading Tips: beginners with poor e can directly read Chinese characters and then copy the code to test. R

To load. 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 element to
Desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:

Function loadjscssfile (filename, filetype ){
If (filetype = "JS") {// determine the file type
VaR fileref = Document. createelement ('script') // create a tag
Fileref. setattribute ("type", "text/JavaScript") // defines the attribute type value as text/JavaScript
Fileref. setattribute ("src", filename) // file address
}
Else if (filetype = "CSS") {// determine the 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") // when the page is opened, the browser dynamically loads the file
Loadjscssfile ("javascript. php", "JS") // when the page is opened, the browser dynamically loads "javascript. php ",
Loadjscssfile ("mystyle.css", "CSS") // the browser's dynamic .css file when opening a page

The next step is to bind to the

In this case, we can add a Global Array variable to store the bound file name in it. Check whether the bound file exists before each binding. If yes, the system prompts that the file already exists, if it does not exist, bind it. R

Document. getelementsbytagname ("head") [0]. appendchild (fileref)

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 shoshould be aware that no existing element is harmed in the adding
Of the new element-that is to say, if you call loadjscssfile ("myscript. JS "," JS ") twice, you now end up with two new" script "elements both pointing to the same Javascript file. this is problematic only from an efficiency standpoint, as you'll be adding redundant
Elements to the page and using unnecessary browser memory in the process. A simple way to prevent the same file from being added more than once is 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 shoshould be aware that no existing element is harmed in the adding of the new
Element-that is to say, if you call loadjscssfile ("myscript. JS "," JS ") twice, you now end up with two new" script "elements both pointing to the same Javascript file. this is problematic only from an efficiency standpoint, as you'll be adding redundant elements
To the page and using unnecessary browser memory in the process. A simple way to prevent the same file from being added more than once is 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 may require that you actually remove or replace an added. js or. CSS file. Lets see how that's done next.

Related Article

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.