Edit this page

up.fragment up.render([target], [options])
JavaScript function

Replaces elements on the current page with matching elements from a server response or HTML string.

Choosing which fragment to update

The current and new elements must both match the same target selector. The selector is either given as { target } option, or a main target is used as default.

Let's say your current HTML looks like this:

<div class="one">old one</div>
<div class="two">old two</div>

We now replace the second <div> by targeting its CSS class:

up.render({ target: '.two', url: '/new' })

The server renders a response for /new:

<div class="one">new one</div>
<div class="two">new two</div>

Unpoly looks for the selector .two in the response and places it the current page. The current page now looks like this:

<div class="one">old one</div>
<div class="two">new two</div>

Note how only .two has changed. The update for .one was discarded, since it didn't match the selector.

See targeting fragments for many examples for how you can target content.

Passing the new fragment

The new fragment content can be passed as one of the following options:

JavaScript option HTML attribute Effect
{ url } [href] or [action] Load a HTML document and extract a fragment
{ content } [up-content] Update an element's inner HTML from a string
{ fragment } [up-fragment] Update an element's outer HTML from a string
{ document } [up-document] Extract an element's outer HTML from a larger HTML string
{ response } Render an up.Response object

See providing content to render for more details and examples.

Enabling side effects

This function has many options to enable scrolling, focus, request cancelation and other side effects. These options are all disabled by default and must be opted into one-by-one.

To enable defaults that a user would expects for navigation (like clicking a link), pass { navigate: true } or use up.navigate() instead.

Hooking into the render process

Your code may hook into specific stages of the rendering process. This allows you to modify the rendered result or handle error cases.

See render hooks for details.

Concurrency

Unfinished requests targeting the updated fragment or its descendants are aborted. You may control this behavior using the { abort } option.

Events

Unpoly will emit events at various stages of the rendering process:


Parameters

[target] stringorElementorjQueryorArray<string> optional

The target selector to update.

If omitted a main target will be rendered.

You may also pass a DOM element or jQuery element here, in which case a selector will be derived. The given element will also be used as { origin } for the fragment update.

You may also pass an array of selector alternatives. The first selector matching in both old and new content will be used.

Instead of passing the target as the first argument, you may also pass it as a { target } option..

[options.target] stringorElementorjQueryorArray<string> optional

The target selector to update.

See documentation for the target parameter.

[options.fallback=false] stringorboolean optional

Specifies behavior if the target selector is missing from the current page or the server response.

If set to a CSS selector string, Unpoly will attempt to replace that selector instead.

If set to true Unpoly will attempt to replace a main target instead.

If set to false Unpoly will immediately reject the render promise.

Also see Dealing with missing targets.

[options.match='region'] string optional

Controls which fragment to update when the { target } selector yields multiple results.

When set to 'region' Unpoly will prefer to update fragments in the region of the origin element.

If set to 'first' Unpoly will always update the first matching fragment.

Defaults to up.fragment.config.match, which defaults to 'region'.

[options.navigate=false] boolean optional

Whether this fragment update is considered navigation.

[options.url] string optional

The URL to fetch from the server.

See loading content from a URL.

Instead of making a server request, you may also render an existing string of HTML.

[options.method='get'] string optional

The HTTP method to use for the request.

Common values are 'get', 'post', 'put', 'patch' and 'delete'. The value is case insensitive.

[options.params] Objectorup.ParamsorFormDataorstringorArray optional

Additional parameters that should be sent as the request's query string or payload.

When making a GET request to a URL with a query string, the given { params } will be added to the query parameters.

[options.headers={}] Object optional

An object with additional request headers.

Unpoly will by default send a number of custom request headers. E.g. the X-Up-Target header includes the targeted CSS selector. See up.protocol for details.

[options.content] stringorElement optional

The new inner HTML for the targeted fragment.

See Updating an element's inner HTML from a string.

[options.fragment] stringorElement optional

A string of HTML comprising only the new fragment's outer HTML.

When passing { fragment } you can omit the { target } option. The target will be derived from the root element in the given HTML.

See Rendering a string that only contains the fragment.

[options.document] stringorElementorDocument optional

A string of HTML containing the targeted fragment.

See Extracting an element's outer HTML from a larger HTML string.

[options.response] up.Response optional

An up.Response object that contains the targeted fragments in its text.

See Rendering an up.Response object.

[options.fail] booleanorFunction(up.Response): boolean optional

Whether the server response should be considered failed.

By default any HTTP status code other than 2xx or 304 is considered an error code.

For failed responses Unpoly will use options prefixed with fail, e.g. { failTarget }. See handling server errors for details.

[options.history] booleanorstring optional

Whether the browser URL, window title and meta tags will be updated.

If set to true, the history will always be updated, using history the server response, or from given { title } and { location } options.

If set to 'auto' history will be updated if the { target } matches a selector in up.fragment.config.autoHistoryTargets. By default this contains all main targets.

If set to false, the history will remain unchanged.

See Updating history.

[options.title] booleanorstring optional

An explicit document title to set before rendering.

By default the title is extracted from the response's <title> tag. To prevent the title from being updated, pass { title: false }

This option is only used when updating history.

[options.location] booleanorstring optional

An explicit browser location URL to set before rendering.

By default Unpoly will use the { url } or the final URL after the server redirected. To prevent the URL from being updated, pass { location: false }.

This option is only used when updating history.

[options.metaTags] booleanorArray<Element> optional

Whether to update meta tags in the <head>.

By default Unpoly will extract meta tags from the response's <head>. To prevent meta tags from being updated, pass { metaTags: false }.

This option is only used when updating history.

[options.transition] string optional

The name of an transition to morph between the old and few fragment.

If you are prepending or appending content, use the { animation } option instead.

[options.animation] string optional

The name of an animation to reveal a new fragment when prepending or appending content.

If you are replacing content (the default), use the { transition } option instead.

[options.duration] number optional

The duration of the transition or animation (in millisconds).

[options.easing] string optional

The timing function that accelerates the transition or animation.

See MDN documentation for a list of available timing functions.

[options.cache] boolean optional

Whether to read from and write to the cache.

With { cache: true } Unpoly will try to re-use a cached response before connecting to the network. To prevent display of stale content, cached responses are reloaded once rendered. If no cached response exists, Unpoly will make a request and cache the server response.

With { cache: 'auto' } Unpoly will use the cache only if up.network.config.autoCache returns true for the request.

With { cache: false } Unpoly will always make a network request.

[options.revalidate] boolean optional

Whether to reload the targeted fragment after it was rendered from a cached response.

With { revalidate: 'auto' } Unpoly will revalidate if the up.fragment.config.autoRevalidate(response) returns true. By default this configuration will return true for expired responses.

With { revalidate: true } Unpoly will always revalidate cached content, regardless of its age.

With { revalidate: false } Unpoly will never revalidate cached content.

[options.expireCache] booleanorstring optional

Whether existing cache entries will be expired with this request.

Defaults to the result of up.network.config.expireCache, which defaults to true for unsafe requests.

To only expire some requests, pass an URL pattern that matches requests to uncache. You may also pass a function that accepts an existing up.Request and returns a boolean value.

[options.evictCache] booleanorstring optional

Whether existing cache entries will be evicted with this request.

Defaults to the result of up.network.config.evictCache, which defaults to false.

To only evict some requests, pass an URL pattern that matches requests to uncache. You may also pass a function that accepts an existing up.Request and returns a boolean value.

[options.abort='target'] booleanorstringorFunction(request): boolean optional

Whether to abort existing requests before rendering.

See aborting requests for details and a list of options.

[options.abortable=true] boolean optional

Whether this request may be aborted by other requests targeting the same fragments or layer.

See aborting requests for details.

[options.background=false] boolean optional

Whether this request will load in the background.

Background requests deprioritized over foreground requests. Background requests also won't emit up:network:late events and won't trigger the progress bar.

[options.badResponseTime] number optional experimental

The number of milliseconds after which this request can cause an up:network:late event and show the progress bar.

Defaults to up.network.config.badResponseTime.

[options.timeout] number optional

The number of milliseconds after which this request fails with a timeout.

Defaults to up.network.config.timeout.

[options.origin] ElementorjQuery optional

The element that triggered the change.

When multiple elements in the current page match the { target }, Unpoly will replace an element in the origin's proximity.

The origin's selector will be substituted for :origin in a target selector.

[options.layer='origin current'] stringorup.LayerorElement optional

The layer in which to match and render the fragment.

See layer option for a list of allowed values.

To open the fragment in a new overlay, pass { layer: 'new' }. In this case options for up.layer.open() may also be used.

[options.peel] boolean optional

Whether to close overlays obstructing the updated layer when the fragment is updated.

This is only relevant when updating a layer that is not the frontmost layer.

[options.context] Object optional

An object that will be merged into the context of the current layer once the fragment is rendered.

[options.scroll] booleanorstringorElementorFunction optional

How to scroll after the new fragment was rendered.

See scrolling for a list of allowed values.

[options.scrollBehavior='instant'] string optional
[options.revealSnap] number optional

When to snap to the top when scrolling to an element near the top edge of the viewport's scroll buffer.

[options.revealTop] number optional

When to move a revealed element to the top when scrolling to an element.

[options.revealPadding] string optional

How much space to leave to the closest viewport edge when scrolling to an element.

[options.revealMax] string optional

How many pixel lines of high element to reveal when scrolling to an element.

[options.saveScroll=true] boolean optional

Whether to save scroll positions before updating the fragment.

Saved scroll positions can later be restored with { scroll: 'restore' }.

[options.focus] booleanorstringorElementorFunction optional

What to focus after the new fragment was rendered.

See Controlling focus for a list of allowed values.

[options.saveFocus=true] boolean optional

Whether to save focus-related state before updating the fragment.

Saved focus state can later be restored with { focus: 'restore' }.

[options.confirm] string optional

A message the user needs to confirm before fragments are updated.

The message will be shown as a native browser prompt.

If the user does not confirm the render promise will reject and no fragments will be updated.

[options.feedback] booleanorElement optional

Whether to give the { origin } element an .up-active class and the targeted element an .up-loading class while loading content.

See navigation feedback.

[options.data] Object optional

Overrides properties from the new fragment's [up-data] with the given data object.

[options.onLoaded] Function(Event) optional

A callback that will be run when the server responds with new HTML, but before the HTML is rendered.

The callback argument is a preventable up:fragment:loaded event.

This callback will also run for failed responses.

[options.onRendered] Function(up.RenderResult) optional

A function to call when Unpoly has updated fragments.

This callback may be called zero, one or two times:

  • When the server rendered an empty response, no fragments are updated. { onRendered } is not called.
  • When the server rendered a matching fragment, it will be updated on the page. { onRendered } is called with the result.
  • When revalidation renders a second time, { onRendered } is called again with the final result.

Also see Running code after rendering.

[options.onFinished] Function(up.RenderResult) optional

A function to call when no further DOM changes will be caused by this render pass.

In particular:

The callback argument is the last up.RenderResult that updated a fragment. If revalidation re-rendered the fragment, it is the result from the second render pass. If no revalidation was performed, or if revalidation yielded an empty response, it is the result from the initial render pass.

Also see Awaiting postprocessing.

[options.onOffline] Function(Event) optional

A callback that will be run when the fragment could not be loaded due to a disconnect or timeout.

The callback argument is a preventable up:fragment:offline event.

[options.onError] Function(Error) optional

A callback that will be run when any error is thrown during the rendering process.

The callback is also called when the render pass fails due to network issues, or aborts.

Also see Handling errors.

[options.useKeep=true] boolean optional experimental

Whether [up-keep] elements will be preserved in the updated fragment.

[options.useHungry=true] boolean optional experimental

Whether [up-hungry] elements outside the updated fragment will also be updated.

Return value

A promise that fulfills with an up.RenderResult once the page has been updated.

If the update is animated, the promise will be resolved before the existing element was removed from the DOM tree. The old element will be marked with the .up-destroying class and removed once the animation finishes. To run code after the old element was removed, pass an { onFinished } callback.