HarryNews HarryNews - 2 years ago 108
Javascript Question

jQuery load vs building elements

I'm working on a webpage, and it has several menus that aren't always visible. As far as I know, there are 3 ways to implement the menus:

1. I can declare the menus in the index.html file, and set their styles to "display: none" and show/hide them as needed. For example:

<div id="div-to-always-show">I want to always show this</div>
<div id="menu-to-sometimes-show" style="display:none">I want to sometimes show this</div>


The downside to this is that the page will have to process a lot of elements that aren't actually effecting the page.
2. I can build the menus in jQuery when they're needed. For example:

$("<div>").text("I want to sometimes show this")

3. I can use .load() to request the menu from the server, and store it in a variable (so I only have to request it once). For example:

var $menu = null;
function showMenu(){
if($menu === null)
$menu = $("<div>").load("menuToSometimesShow.html");
function hideMenu(){

So my question is: is there any reason to choose one method over the others?

Answer Source
  1. to include it in the HTML and hide the element either indirectly by a class or directly via display:none; depending on the case is mostly the way to go if your menu isn't too big, e.g. includes just a handful of links.

  2. Of course it's a matter of taste if you but HTML in JavaScript, but I would definitely recommend to try to keep HTML where it should be as much as possible. And to but only the necessary part into a script file. It's not just slower - you will still have to submit all the data, so you're not having a real advantage.

  3. when you load big menus, maybe with one or several sub menus, maybe even including images then it definitely makes sense to handle this via seperate AJAX requests. In more complex cases it makes even sense to only submit parts of the menu on need, e.g. you don't need submenu 2 to 9 if just 1 has been clicked.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download