`

Dynamically loading external JavaScript and CSS files

    博客分类:
  • js
 
阅读更多

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 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:

 

function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        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") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

 Since external JavaScript and CSS files can technically end with any custom file extension (ie: "javascript.php"), the function parameter "filetype" lets you tell the script what file type to expect before loading. After that, the function sets out to create the element using the appropriate DOM methods, assign it the proper attributes, and finally, add it to the end of the HEAD section. Now, where the created file gets added is worth elaborating on:

 

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 should 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:

 

var filesadded="" //list of files already added
 
function checkloadjscssfile(filename, filetype){
    if (filesadded.indexOf("["+filename+"]")==-1){
        loadjscssfile(filename, filetype)
        filesadded+="["+filename+"]" //List of files added in the form "[filename1],[filename2],etc"
    }
    else
        alert("file already added!")
}
 
checkloadjscssfile("myscript.js", "js") //success
checkloadjscssfile("myscript.js", "js") //redundant file, so file not added

 

分享到:
评论

相关推荐

    Beginning JavaScript with DOM Scripting and Ajax: Second Editon

    Beginning JavaScript with DOM Scripting and Ajax is an essential resource for modern JavaScript programming. This completely updated second edition covers everything you need to know to get up-to-...

    Beginning JavaScript with DOM Scripting and Ajax (pdf + ePub)

    Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition (pdf + ePub) by Russ Ferguson and Christian Heilmann Publisher: Apress; 2nd Edition (July 2013) Language: English ISBN-10: 1430250925 ...

    Dynamically loading classes from DLLs(7KB)

    动态加载DLL(Dynamic Link Library)中的类是一种在运行时按需加载代码的机制,它可以提高程序的灵活性,减少应用程序的启动时间和内存占用。这个压缩包包含的文件是关于如何实现这一功能的源代码示例。...

    Java.EE.and.HTML5.Enterprise.Application.Development

    Find out how to navigate NetBeans IDE, construct HTML5 programs, employ JavaScript APIs, integrate CSS and WebSockets, and handle security. This Oracle Press guide also offers practical coverage of ...

    Dynamically Centering and Alignment.zip

    "Dynamically Centering and Alignment.zip"这个压缩包文件显然包含了关于如何在HTML5 Canvas上实现这一目标的教程或代码示例。Canvas是JavaScript提供的一种强大的图形绘制API,通过它可以进行像素级别的图形操作。...

    Dynamic Class Loading in the JavaTM Virtual Machine

    Class loaders are a powerful mechanism for dynamically loading software components on the Java platform. They are unusual in supporting all of the following features: laziness, type-safe linkage, user...

    EXECUTABLE AND LINKABLE FORMAT

    ELF object files contain sections that define data, code, symbols, and other metadata necessary for linking and loading processes. #### ELF Header The ELF header is a critical part of an ELF file ...

    【船级社】 ABS Design and Installation of Dynamically Installed Piles

    【船级社】 ABS Design and Installation of Dynamically Installed Piles Dynamically_Installed_Piles_Corrigenda-Mar18.pdf

    JavaScript in 10 Minutes

    ### JavaScript in 10 Minutes: Key Insights for Intermediate and Advanced Programmers #### Introduction "JavaScript in 10 Minutes" is a concise guide that aims to provide intermediate to advanced ...

    [Dreamweaver] Dreamweaver CS5.5 实战手册 (英文版)

    Use powerful, easy-to-use tools such as CSS3 and Spry effects to build visually rich, fast-loading pages. - Add instant interactivity. Choose from pre-packaged JavaScript programs to add drop-down ...

    JavaScript APIs HTML5

    The Canvas API allows developers to dynamically render graphics and images on a canvas element. It provides a powerful set of tools for drawing and manipulating images and shapes. The basic setup ...

    phpmaker610官方安装版

    Server-side validation and/or client-side JavaScript validation Optional search features (Quick, Extended Quick and Advanced) with search result highlight Optional User ID and User Level Advanced ...

    angular-boilerplate:用于构建 AngularJS 应用程序的样板项目

    角样板 AngularJS 项目的样板。 安装节点 安装node后,全局安装Gulp npm install gulp -g 安装所有依赖 npm install ... build-html Dynamically injects javascript and css files clean

    An Efficient Dynamically Adaptive Mesh for potentially singular solutions

    ### 动态自适应网格技术在潜在奇异性解中的高效应用 #### 摘要与背景 本文介绍了一种高效动态自适应网格生成方法,旨在解决时间依赖问题中出现的复杂结构甚至奇异性行为。该方法的核心是通过求解一组非线性椭圆偏...

    teracopy2b4

    TeraCopy is a compact program designed to copy and move files at the maximum possible speed, providing the user a lot of features: Copy files faster. TeraCopy uses dynamically adjusted buffers to ...

    Jack Spurlock - Bootstrap

    With just a basic knowledge of HTML, CSS, and JavaScript, you can build apps that work equally well on desktop screens, smartphones, and tablets. This book shows you how. Become familiar with ...

Global site tag (gtag.js) - Google Analytics