一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

JavaScript动态创建link标签到head里(延时加载)

时间:2014-01-15 编辑:简简单单 来源:一聚教程网

使用 jQuery 创建 link 标签

如果你开发中喜欢用jQuery,那么用jQuery在创建link标签应该是这样的:

 代码如下 复制代码

var cssURL = '/style.css',
    linkTag = $('');

// 请看清楚,是动态将link标签添加到head里   
$($('head')[0]).append(linkTag);   

使用原生 JavaScript 创建 link 标签

如果你喜欢纯天然的 JavaScript,就要需要这么写:

 代码如下 复制代码

var head = document.getElementsByTagName('head')[0],
    cssURL = '/style.css',
    linkTag = document.createElement('link');
 
    linkTag.id = 'dynamic-style';
 linkTag.href = cssURL;
 linkTag.setAttribute('rel','stylesheet');
 linkTag.setAttribute('media','all');
 linkTag.setAttribute('type','text/css');
 
head.appendChild(linkTag); 

IE 里特有的方法 createStyleSheet

IE 里特有的方法 createStyleSheet 方法也是很方便。

 代码如下 复制代码

var head = document.getElementsByTagName('head')[0],
    cssURL = 'themes/BlueNight/style.css',
 // document.createStyleSheet www.111Cn.net的同时就已经把link标签添加到了head中了,怎么讲呢,倒是挺方便
    linkTag = document.createStyleSheet(cssURL);

createStyleSheet( [sURL] [, iIndex])方法接受两个参数,sURL就是CSS文件的URL路径。iIndex 为可选参数,指插入的link在页面中stylesheets collection的索引位置,默认是在最后添加新创建的样式。


完整的解决方案

基本上都介绍完了,来看看完整的解决方案吧:

 代码如下 复制代码

 
function createLink(cssURL,lnkId,charset,media){ 
var head = $($('head')[0]),
    linkTag = null;
 
 if(!cssURL){
     return false;
 }
 
 linkTag = $('');
  
 head.append(linkTag);
}

function createLink(cssURL,lnkId,charset,media){ 
    var head = document.getElementsByTagName('head')[0],
        linkTag = null;
  
 if(!cssURL){
     return false;
 }
    
    linkTag = document.createElement('link');
 linkTag.setAttribute('id',(lnkId || 'dynamic-style'));
 linkTag.setAttribute('rel','stylesheet');
 linkTag.setAttribute('charset',(charset || 'utf-8'));
 linkTag.setAttribute('media',(media||'all'));
 linkTag.setAttribute('type','text/css');
    linkTag.href = cssURL; 
 
    head.appendChild(linkTag); 
}

热门栏目