Last active
December 13, 2015 18:49
-
-
Save MaraScott/4958244 to your computer and use it in GitHub Desktop.
Name : checkloadjscssfile(filename, filetype) - Language : JavaScript - type : function - platform : generic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// see : http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml | |
// Load a js or a css file | |
var filesadded = "", //list of files already added | |
fileref = ""; | |
function checkloadjscssfile (filename, filetype) { | |
"use strict"; | |
if (filesadded.indexOf("[" + filename + "]") === -1) { | |
if (loadjscssfile(filename, filetype)) { | |
filesadded += "[" + filename + "]"; //List of files added in the form "[filename1],[filename2],etc" | |
return true; | |
} else { | |
return false; | |
} | |
} else { | |
return false; | |
} | |
} | |
// Load a js or a css file | |
function loadjscssfile(filename, filetype) { | |
"use strict"; | |
fileref = ""; | |
if (filetype === "js") { //if filename is a external JavaScript file | |
fileref = document.createElement('script'); | |
fileref.setAttribute("type", "text/javascript"); | |
fileref.setAttribute("src", filename); | |
} else if (filetype === "css") { //if filename is an external CSS file | |
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); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
// example | |
checkloadjscssfile("myscript.js", "js"); //dynamically load and add this .js file | |
checkloadjscssfile("javascript.php", "js"); //dynamically load "javascript.php" as a JavaScript file | |
checkloadjscssfile("mystyle.css", "css"); ////dynamically load and add this .css file | |
checkloadjscssfile("myscript.js", "js"); //dynamically load and add this .js file | |
checkloadjscssfile("javascript.php", "js"); //dynamically load "javascript.php" as a JavaScript file | |
checkloadjscssfile("mystyle.css", "css"); ////dynamically load and add this .css file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment