docs

Instantiation of Fragments

OpenUI5 provides two options to instantiate a fragment: If it is instantiated inside a controller extending sap.ui.core.mvc.Controller, the loadFragment() function is the way to go. However, if it is instantiated in a non-controller artefact, the generic function sap.ui.core.Fragment.load() can be used.

When comparing fragments to views, a key difference is that fragments are no controls. Views are control instances with their own HTML, properties, and the ability to contain other controls. In contrast, fragments consist solely of their content.

For example, if a fragment containing a button is instantiated, the result is simply the button itself.


Instantiation of Fragments in a Controller

Since 1.93, the loadFragment() function is available on every controller instance extending sap.ui.core.mvc.Controller. This API has several advantages over the generic sap.ui.core.Fragment.load() function:


Loading XML Fragments

To load an XML fragment, use the following syntax:

this.loadFragment({
    name: "myapp.fragments.MyXMLFragment"
});

Note:

The loadFragment() API uses “XML” as the default fragment type. In this example, the XML fragment is identified by a resource name that maps to the resource path myapp/fragments/MyXMLFragment.fragment.xml. This should not be confused with its actual file location, which is typically webapp/fragments/MyXMLFragment.fragment.xml.


Loading JS Fragments

For JS fragments, use the module name syntax:

this.loadFragment({
    name: "module:myapp/fragments/MyJSFragment"
});

Note:

In this example, the JS fragment is identified by the resource name myapp/fragments/MyJSFragment.js. This should not be confused with its actual file location, which is typically webapp/fragments/MyJSFragment.js.


Generic Instantiation of Fragments

The generic function sap.ui.core.Fragment.load() can be called with either the name, the type, and optionally a controller, or with a configuration object and an optional controller; for more information, see the API Reference.

It returns a Promise resolving with either the root control contained in the fragment or an array of root controls.

The different methods used for the instantiation of a fragment have the following commonalities:

Note:

When using the generic function sap.ui.core.Fragment.load() the application developer has to take care to add fragment content only to non-destroyed content:

// Sample for loading an XML Fragment
Fragment.load({
    name: "myapp.fragments.MyFragment"
 }).then(function(oContent){
    if(!this.isDestroyStarted()){
       // do stuff
   }
});

Related Information

API Reference: sap.ui.core.mvc.Controller.prototype.loadFragment

API Reference: sap.ui.core.Fragment.load