Home > Article > Web Front-end > How to introduce css external files in js
How to introduce css external files into js: write it as a custom function, url is the file path, and can be called by future elements. The code is [var script = document.createElement('script')].
This method is suitable for all brands of computers
js Method to introduce css external files:
Write it as a custom function (url is the file path) for later elements to call:
//加载外部css文件 function dynamicLoadCss(url) { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.type='text/css'; link.rel = 'stylesheet'; link.href = url; head.appendChild(link); } dynamicLoadCss("文件路径"); //自动调用函数; //加载外部js文件 function dynamicLoadJs(url) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type='text/jajvascript'; script.href = url; head.appendChild(script); } dynamicLoadCss("文件路径"); //自动调用函数;
Note:
js Whether the script file is placed in the head tag or in the body tag can be selected according to development needs;
The main knowledge points used are: the creation of elements and the addition of elements
document.createElement("元素名称");
document.createElement("元素名称");
In fact, the methods for externally introducing js script files or external css styles are similar.
It’s just that externally imported css files can only be placed within the head tag, while js can be placed within the head tag, within the body tag, or outside the html tag.
Related learning recommendations: js video tutorial(free)
The above is the detailed content of How to introduce css external files in js. For more information, please follow other related articles on the PHP Chinese website!