Dynamically loading an external JavaScript or CSS file using function

  • 5 years-11 months

    Dynamically loading an external JavaScript or CSS file using function

    • Category : php
    • Viewed : 91 times
    • Posted On :
    • Posted by : Vikas

    To load a .js or .css file dynamically, in a head section, it means using DOM methods to first create a new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together

    <script type="text/javascript">
    // function
    function loadheadfile(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)
    }
    
    
    // call function
    loadheadfile('https://tsuyoshiwada.github.io/sweet-scroll/lib/icomoon/style.css','css');
    </script>
     

Report this or Ask your own question

Your Answer

When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.