Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js 动态加载 / 移除 script 与 link 文件 #15

Open
ahaow opened this issue Apr 17, 2019 · 0 comments
Open

js 动态加载 / 移除 script 与 link 文件 #15

ahaow opened this issue Apr 17, 2019 · 0 comments

Comments

@ahaow
Copy link
Owner

ahaow commented Apr 17, 2019

js 动态加载 / 移除 script 与 link 文件

使用场景

在 知乎日报 获取 新闻详情的 数据中,例如:https://news-at.zhihu.com/api/4/news/9710258

数据格式:

css样式表是给以链接的方式给前端的,这就需要我们动态创建script 或者 link标签来引入 css 或者 js

css动态引入/移除

// 引入

function loadCss(href) {

	var link = document.createElement("link");
	link.setAttribute("rel","stylesheet");
	link.setAttribute("type","text/css");
	link.setAttribute("href",href);

	var heads = document.getElementsByTagName("head");

	if(heads.length) {
		heads[0].appendChild(link);
	} else {
		document.documentElement.appendChild(link);
	}
}


// 移除

function removeCss(href) {
	var links = document.getElementByTagName("link");
	for(var i = 0; i < links.length; i++ ) {
		if(links[i] && links[i].href && links[i].href.indexOf(href) != -1) {
			links[i].parentNode.removeChild(links[i]);
		}
	}
}

动态创建style方式

function addCssByStyle(cssString){ 
    var doc=document; 
    var style=doc.createElement("style"); 
    style.setAttribute("type", "text/css"); 
   
    if(style.styleSheet){// IE 
        style.styleSheet.cssText = cssString; 
    } else {// w3c 
        var cssText = doc.createTextNode(cssString); 
        style.appendChild(cssText); 
    } 
   
    var heads = doc.getElementsByTagName("head"); 
    if(heads.length) 
        heads[0].appendChild(style); 
    else 
        doc.documentElement.appendChild(style); 
} 

js动态引入/移除

// 引入

function loadScript(src) {

	var addSign = true;

	var script = document.getElementsByTagName("script");

	for(var i = 0; i < script.length; i++) {
		if(script[i] && script[i].src && script[i].src.indexOf(src) != -1) {
			return addSign = false;
		}
	}
	if(addSign) {
		var newScript = document.createElement("script");
		newScript.setAttribute("type","text/javascript");
		newScript.setAttribute("src",src);
		document.getElementsByTagName("head")[0].appendChild(newScript);
	}
}

// 移除

function removeScript(src) {

	var scripts = document.getElementsByTagName("script");
	for (var i = 0; i < scripts.length; i++) {
        if (scripts[i] && scripts[i].src && scripts[i].src.indexOf(src) != -1) {
            scripts[i].parentNode.removeChild(scripts[i]);
        }
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant