---
title: "Loading CSS and JS files using JavaScript"
url: https://www.geekcorelab.cn/en-US/post/using-javascript-to-load-css-and-js-files
updated: 2026-11-08T08:02:57.663850Z
author: "hhjmk"
summary: "文章介绍了两种JavaScript函数用于加载网页资源，包括加载CSS文件和加载JS文件。加载CSS文件函数创建link元素并设置相关属性后添加到head中，加载JS文件函数创建script元素并设置属性后同样添加到head中。文章通过示例展示了如何使用这两个函数加载指定的CSS和JS文件，实现网页资源的动态加载。"
---

# Loading CSS and JS files using JavaScript

```
//加载css文件函数 
function link(url) {
  var link = document.createElement("link");
  link.rel = "stylesheet";
  link.type = "text/css";
  link.href = url;
  document.getElementsByTagName("head")[0].appendChild(link);
}
//加载css文件函数 

//加载js文件函数 
function script(url) {
  var newscript = document.createElement('script');
  newscript.setAttribute('type','text/javascript');
  newscript.setAttribute('src',url);
  var head = document.getElementsByTagName('head')[0];
  head.appendChild(newscript);
}
//加载js文件函数 

script("js文件链接");
//执行加载js文件
link("css文件的链接");
//执行加载css文件
```
