简体   繁体   中英

Why doesn't javascript have an include, require, or import function?

Sticking with the concept of separating html, from php and javascript per best coding practices, I'm finding it quite inconvenient to include my javascript files like this: <script src="../../lib/javascript/jquery.min.js"></script>

The reason is that I'm refactoring a large project that isn't easily maintained at the moment. Part of this includes separating a lot out into more managable chunks:

在此处输入图片说明

Here's the main folder of concern:

在此处输入图片说明

Long story short, I'm having difficulty figuring out how to include and sort of nest my javascript, in a similar fashion to php import for example. For example, my logon page uses users.js to run a function to check the user credentials; and users.js uses alerts.js to display any problems. The problem is that, currently, I only know how to include and link all these files together using html in the login page like so:

<script src="../../lib/javascript/jquery.min.js"></script>
<script src="../../lib_bh/javascript/alerts.js"></script>
<script src="../../lib_bh/javascript/users.js"></script>

But this doesn't seem right since alerts is only used by users.js functions on this page and not the page itself. I could use the above script tags in user.js to fix this, but then I'm turning what was intended to be a js library into an html file, and that doesn't seem right ether. I've been looking at ES6 syntax and it looks promising, but there isn't a lot of talk about it so I'm concerned (and confused) about how to use it. Basically, how do I nest my javascript so that I can separate functions and code of different types to be used throughout all my pages in a dynamic way. Heck, I would much rather include jquery instead of using the script tag too... reading about doing that caused concerns ( https://github.com/DefinitelyTyped/DefinitelyTyped/issues/6315 ) so I feel like I'm at a brick wall. Thanks.

I think I sort of answered my own question. If you use a callback and pass the data back, it fixes this programming issue. Makes it so that including all javascript code references directly in the page make sense. ie Thanks to the callback function, one js file never need be dependent on another.

You can use HTML Imports:

<link rel="import" href="include.html">

Then in the referenced file (here: include.html ), put all the Javascript and CSS files you need.

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