Sogrey / Web-QA

https://sogrey.github.io/Web-QA/
MIT License
6 stars 2 forks source link

如何用JavaScript动态创建link标签到head里? #148

Open Sogrey opened 4 years ago

Sogrey commented 4 years ago

jQuery:

function createLink(cssURL,lnkId,charset,media){ 
var head = $($('head')[0]),
    linkTag = null;

 if(!cssURL){
     return false;
 }

 linkTag = $('<link href="' + cssURL + '" rel="stylesheet" type="text/css" media="' + (media || "all") + '" charset="'+ charset || "utf-8" +'" />');

 head.append(linkTag);
}

javascript:

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); 
}
Sogrey commented 4 years ago

149