Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

javascript - Fetching html instead import js module - why or why not?

I have a technical debate ongoing and a decision needs to be taken, but I hardly have any facts to decide on, only opinions like

"That's not the way one should work" or "This is bad practise"

But this doesn't help me to decide on the following problem:

We are to build a SPA not using any frameworks or packages like webpack, so from scratch / vanillaJS. Basically I have an index.html loading a main.js as entry point which will then load the page requested via Hash in the browsers location replacing the content of a <div id="content">...</div>. So far so good, just a simple SPA.

Now the question is whether to:

  1. Load standalone .html files (e.g. somepage.html) via fetch (remember no webpack, all vanilla...) and DOM parse them, extract any script tags (e.g. <script src="somepage.js" type="module">) and put the remaining html code in the <div id="content">...</div>, add scripts to the head and so on...

or

  1. Have a simple router in our index.js which has ES6 module imports for each available page, so basically import a JS module which will have a html template somehow referenced (as a string or loaded via fetch) and add HTML to the <div id="content">...</div>, call the JS modules init()-function and so on...

I would always tend to say: Use the second way, avoid fetching full html pages. But why?

My only arguments so far:

  • why fetching more data than necessary - the most of the html (like ...) is unnecessary overhead
  • do not switch between languages more than absolutely necessary, since in way 1 you load HTML (index.html), then JS (index.js), then again HTML (somePage.html), then again JS (somePage.js) and every switch means interfaces need to be considered and handled, so they could mean less control over your code

But that can't be it and doesn't really convince me - what are the hard facts why or why not doing this ways?

(and sorry if this is not an appropriate question - I'm just new here)

question from:https://stackoverflow.com/questions/65916224/fetching-html-instead-import-js-module-why-or-why-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...