Can .js file “include” another .js file [duplicate

2019-04-03 09:43发布

In PhP you can.

In html, you sort of can with <script src="..."> tag

but what about if we have a .js file and we want to include another .js file. How would we do so?

1条回答
贼婆χ
2楼-- · 2019-04-03 10:12

If you mean in a browser context, not directly, but you can use a loader like at RequireJS (there are several).

Or to do it manually:

var script = document.createElement('script');
script.src = "/path/to/the/other/file.js";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);

Note, though,that with the above the functions and such in the other file won't be available for use right away. The code above starts the process of loading the file, but it continues asynchronously. You can use events to know that the load is complete (primarily the load event, but on older versions of IE you have to use onreadystatechange -- this is one reason people use loaders!).

查看更多
登录 后发表回答