admin管理员组

文章数量:1201402

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?

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?

Share Improve this question edited Jan 17, 2017 at 9:36 Mistalis 18.3k13 gold badges77 silver badges97 bronze badges asked Jan 3, 2016 at 17:58 nikoniko 1,1681 gold badge12 silver badges26 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 24

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.

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.

本文标签: javascriptMaterial Design Lite JS not applied to dynamically loaded html fileStack Overflow