如何实现在HTML中使用defer属性,这样JS文件会在文档解析后再执行,而servlet会在JS之前执行。
时间: 2024-02-18 10:05:36 浏览: 25
在HTML中使用defer属性,可以让浏览器在解析HTML文档的同时,异步下载JS文件,等到HTML文档解析完成后再执行JS文件。这样可以确保JS文件的执行在servlet之后。
具体实现方法如下:
1. 在HTML文档中引入JS文件时,添加defer属性:
```html
<script src="your-script.js" defer></script>
```
2. 在需要执行JS代码的地方,添加JS代码:
```html
<script>
// your JS code here
</script>
```
3. 在servlet中返回HTML文档,确保JS文件在HTML文档中的位置在servlet的代码之前:
```java
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Your Title</title>");
out.println("<script src=\"your-script.js\" defer></script>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("<script>");
out.println("// your JS code here");
out.println("</script>");
out.println("</body>");
out.println("</html>");
```
这样就可以确保JS文件在文档解析后再执行,而servlet会在JS之前执行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)