简体   繁体   中英

JavaScript file doesn't load

I'm using Spring MVC, Thymeleaf and want to import a javascript file in my html document. Although all links are set correctly and the files appear in the debugging view in my browser, they don't load. There is following JS in the HTML that should call a datepicker, but it doesn't show up:

<script th:inline="javascript">
/*<![CDATA[*/
  $( function() {
    $( "#datepicker" ).Datepicker(
      );
  } );
/*]]>*/
</script>

the files are included this way:

  <script type="text/javascript" th:src="@{/resources/js/file.js}"></script>

CSS files work just fine just with the type changed.

Any ideas how to fix this?

Shows error on Chrome debugging

Now I deleted all not necessary js files from the import and it shows following error:

more precise error

This shows that the jquery-1.12.4 is used.

The Answer:

1) <th:block></th:block> makes no diffrence

2) The additions to the html tag

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"

make no difference

3) placing the script-tags with content at the bottom of the body is the same as when placing it in the head

4) I use Bootstrap in this project and used the datepicker inside a div of Bootstrap. After placing it somewhere else in the body and not inside a div it worked.

Conclusion: If you are using Spring MVC and Thymeleaf and want to include JavaScript files you need:

1) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >

2) <link th:href="@{/resources/.../file.css}" rel="stylesheet" type="text/css"/>

3) <script type="text/javascript" th:src="@{/resources/.../file.js}"></script>

4) Make sure your JS or CSS files are not "overwritten" by following files

Thanks for your time and help @Parth!

When you are using Spring and Thymeleaf the following project structure is recommended:

src
   |-main
       |-resources
           |-static
           |   |-css
           |       |-bootstrap.min.css
           |       |-application.css
           |   |-images
           |   |-js
           |       |-jquery-3.1.1.js
           |-templates

Then including different resources in your templates will look like this:

<head>
    <link href="../static/css/bootstrap.min.css" rel="stylesheet" media="screen"
          th:href="@{/css/bootstrap.css}"/>
    <link href="../static/css/application.css" rel="stylesheet" media="screen"
          th:href="@{/css/application.css}"/>

    <script src="../static/js/jquery-3.1.1.js"
            th:src="@{/js/jquery-3.1.1.js}"></script>
</head>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM