11

I want to unify the navigation layout for my website, so I created a separate html file that holds the code for the navigation. I use a JS to load the file dynamically:

$("#navigation").load("/navigation/navigation.html", function() {
   $.getScript('/material.min.js');
});

The problem is that the material.min.js does not get executed for the dynamically loaded components inside this html and I lose some crucial functionality. How do I fix that?

Mistalis
  • 16,351
  • 13
  • 68
  • 91
niko
  • 1,048
  • 1
  • 11
  • 24

2 Answers2

23

Check if the componentHandler is loaded, and try to upgrade the elements after load.

if(!(typeof(componentHandler) == 'undefined')){
  componentHandler.upgradeAllRegistered();
}

How the Component Handler works

In short this goes over all registered components. Queries for all nodes with the provided CSS class. Loops over those and instantiates them one-by-one. When the upgrade is done on a node, the upgraded object is added to the dataset. This object contains a comma separated list of component classAsString properties to identify which upgrades have been done.

Wladimir Palant
  • 53,866
  • 11
  • 93
  • 123
Jimmy Pauwaert
  • 351
  • 2
  • 4
2

From the official docs:

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function.

So loading the material.js script again will not execute it. But you can do some experiments with upgradeElements by applying it to the whole loaded markup or to particular elements.

Rango
  • 3,728
  • 2
  • 20
  • 32
  • I tried that on each descendant element but it has no result. I think I read somewhere on github that `upgradeElement` does not work for layout classes, but I might be wrong... – niko Jan 04 '16 at 19:33
  • Honestly, I just noticed that the example given at the bottom here: http://www.getmdl.io/started/index.html#dynamic does not work if you open the provided CodePen link... – niko Jan 04 '16 at 23:03
  • Just found interesting phrase of one of MDL collaborators: _At least for now, MDL is aimed at static content-heavy websites. So dynamically adding tabs is definitely not a first-class citizen in terms of support._ Why don't you generate the entire html on the server side? – Rango Jan 05 '16 at 06:22