简体   繁体   English

如何从播放后端动态加载 javascript 文件到浏览器?

[英]How to dynamically load javascript files from play backend to browser?

Essentially what I'm looking to do is to have a server store a bunch of assets in a folder structure such as基本上我想要做的是让服务器将一堆资产存储在文件夹结构中,例如

asset
  |
  folder1
     - test1.js
     - test2.js
  folder2
     - test3.js

and be able to return this entire folder tree and the minimized js code via a REST endpoint that can be called by a javscript front end.并且能够通过 javscript 前端可以调用的 REST 端点返回整个文件夹树和最小化的 js 代码。 Ie, GET /dependencies should return all these files and have them be available to be used in client-side javascript files.即, GET /dependencies应该返回所有这些文件,并让它们可用于客户端 javascript 文件。

ie Some file being served up in the front-end might need to use what's inside test1.js .即前端提供的某些文件可能需要使用test1.js中的内容。

How could I go about doing this?我怎么能 go 这样做呢? The backend is completely java so I'm not entirely sure how to serve up full folders full of javascript to be able for the front-end to use.后端完全是 java 所以我不完全确定如何提供充满 javascript 的完整文件夹以供前端使用。 Would I just copy all the files as plaintext, send it over and enclose it in the front end with <script></script> tags?我是否只需将所有文件复制为纯文本,将其发送并用<script></script>标签将其包含在前端?

Would a solution such as the one provided in Loading remote JavaScript file in a page be more efficient?诸如在页面中加载远程 JavaScript 文件中提供的解决方案会更有效吗? or making a GET request from within a <script> tag in my index.html ?或者从我的 index.html 的 <script> 标记中发出 GET 请求

You should make every file accessible vie GET using a unique URL.您应该使用唯一的 URL 使每个文件都可以通过 GET 访问。 I don't know about the implementation in Java but I am sure there is a way to serve a whole directory.我不知道 Java 中的实现,但我确信有一种方法可以提供整个目录。

Using your folder structure a GET request to /assets/folder1/test1.js should return the file contents oft test1 as plain text or even encoded as Javascript like HTML is encoded as text/html .使用您的文件夹结构,对/assets/folder1/test1.js的 GET 请求应将 test1 的文件内容作为纯文本返回,甚至编码为 Javascript ,如 HTML 编码为text/html

You can then build a second endpoint called /dependencies which returns the paths to all the files as an array from which you can query every script using the method described in this answer: https://stackoverflow.com/a/8578840/7846567然后,您可以构建一个名为/dependencies的第二个端点,它将所有文件的路径作为数组返回,您可以使用此答案中描述的方法查询每个脚本: https://stackoverflow.com/a/8578840/7846567

Would I just copy all the files as plaintext, send it over and enclose it in the front end with tags?我是否可以将所有文件复制为纯文本,将其发送过来并用标签将其附在前端?

Yes that is basically what I described.是的,这基本上就是我所描述的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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