Dynamic Loading of external CSS or JS files

Source: Internet
Author: User

 

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

VaR filesadded = "" // Save the array variable of the name of the bound File
Function checkloadjscssfile (filename, filetype ){
If (filesadded. indexof ("[" + filename + "]") =-1) {// indexof checks whether an item exists in the array.
Loadjscssfile (filename, filetype)
Filesadded + = "[" + filename + "]" // Add the file name to filesadded
}
Else
Alert ("file already added! ") // Prompt if it already exists
}
Checkloadjscssfile ("myscript. js", "JS") // success
Checkloadjscssfile ("myscript. js", "JS") // redundant file, so file not added

 

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.