• Stars
    star
    932
  • Rank 49,020 (Top 1.0 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 12 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An AMD loader plugin for loading text resources

text

A RequireJS/AMD loader plugin for loading text resources.

Known to work in RequireJS, but should work in other AMD loaders that support the same loader plugin API.

Docs

See the RequireJS API text section.

Latest release

The latest release is always available from the "latest" tag.

It can also be installed using volo:

volo add requirejs/text

If using npm:

npm install requirejs/text

Usage

It is nice to build HTML using regular HTML tags, instead of building up DOM structures in script. However, there is no good way to embed HTML in a JavaScript file. The best that can be done is using a string of HTML, but that can be hard to manage, particularly for multi-line HTML.

The text.js AMD loader plugin can help with this issue. It will automatically be loaded if the text! prefix is used for a dependency. Download the plugin and put it in the app's baseUrl directory (or use the paths config to place it in other areas).

You can specify a text file resource as a dependency like so:

require(["some/module", "text!some/module.html", "text!some/module.css"],
    function(module, html, css) {
        //the html variable will be the text
        //of the some/module.html file
        //the css variable will be the text
        //of the some/module.css file.
    }
);

Notice the .html and .css suffixes to specify the extension of the file. The "some/module" part of the path will be resolved according to normal module name resolution: it will use the baseUrl and paths configuration options to map that name to a path.

For HTML/XML/SVG files, there is another option. You can pass !strip, which strips XML declarations so that external SVG and XML documents can be added to a document without worry. Also, if the string is an HTML document, only the part inside the body tag is returned. Example:

require(["text!some/module.html!strip"],
    function(html) {
        //the html variable will be the text of the
        //some/module.html file, but only the part
        //inside the body tag.
    }
);

The text files are loaded via asynchronous XMLHttpRequest (XHR) calls, so you can only fetch files from the same domain as the web page (see XHR restrictions below).

However, the RequireJS optimizer will inline any text! references with the actual text file contents into the modules, so after a build, the modules that have text! dependencies can be used from other domains.

Configuration

XHR restrictions

The text plugin works by using XMLHttpRequest (XHR) to fetch the text for the resources it handles.

However, XHR calls have some restrictions, due to browser/web security policies:

  1. Many browsers do not allow file:// access to just any file. You are better off serving the application from a local web server than using local file:// URLs. You will likely run into trouble otherwise.

  2. There are restrictions for using XHR to access files on another web domain. While CORS can help enable the server for cross-domain access, doing so must be done with care (in particular if you also host an API from that domain), and not all browsers support CORS.

So if the text plugin determines that the request for the resource is on another domain, it will try to access a ".js" version of the resource by using a script tag. Script tag GET requests are allowed across domains. The .js version of the resource should just be a script with a define() call in it that returns a string for the module value.

Example: if the resource is 'text!example.html' and that resolves to a path on another web domain, the text plugin will do a script tag load for 'example.html.js'.

The requirejs optimizer will generate these '.js' versions of the text resources if you set this in the build profile:

optimizeAllPluginResources: true

In some cases, you may want the text plugin to not try the .js resource, maybe because you have configured CORS on the other server, and you know that only browsers that support CORS will be used. In that case you can use the module config (requires RequireJS 2+) to override some of the basic logic the plugin uses to determine if the .js file should be requested:

requirejs.config({
    config: {
        text: {
            useXhr: function (url, protocol, hostname, port) {
                //Override function for determining if XHR should be used.
                //url: the URL being requested
                //protocol: protocol of page text.js is running on
                //hostname: hostname of page text.js is running on
                //port: port of page text.js is running on
                //Use protocol, hostname, and port to compare against the url
                //being requested.
                //Return true or false. true means "use xhr", false means
                //"fetch the .js version of this resource".
            }
        }
    }
});

Custom XHR hooks

There may be cases where you might want to provide the XHR object to use in the request, or you may just want to add some custom headers to the XHR object used to make the request. You can use the following hooks:

requirejs.config({
    config: {
        text: {
            onXhr: function (xhr, url) {
                //Called after the XHR has been created and after the
                //xhr.open() call, but before the xhr.send() call.
                //Useful time to set headers.
                //xhr: the xhr object
                //url: the url that is being used with the xhr object.
            },
            createXhr: function () {
                //Overrides the creation of the XHR object. Return an XHR
                //object from this function.
                //Available in text.js 2.0.1 or later.
            },
            onXhrComplete: function (xhr, url) {
                //Called whenever an XHR has completed its work. Useful
                //if browser-specific xhr cleanup needs to be done.
            }
        }
    }
});

Forcing the environment implementation

The text plugin tries to detect what environment it is available for loading text resources, Node, XMLHttpRequest (XHR) or Rhino, but sometimes the Node or Rhino environment may have loaded a library that introduces an XHR implementation. You can force the environment implementation to use by passing an "env" module config to the plugin:

requirejs.config({
    config: {
        text: {
            //Valid values are 'node', 'xhr', or 'rhino'
            env: 'rhino'
        }
    }
});

License

MIT

Code of Conduct

jQuery Foundation Code of Conduct.

Where are the tests?

They are in the requirejs and r.js repos.

History

This plugin was in the requirejs repo up until the requirejs 2.0 release.

More Repositories

1

requirejs

A file and module loader for JavaScript
JavaScript
12,930
star
2

r.js

Runs RequireJS in Node and Rhino, and used to run the RequireJS optimizer
JavaScript
2,568
star
3

almond

A minimal AMD API implementation for use after optimized builds
JavaScript
2,414
star
4

example-multipage

Example RequireJS-based project that has multiple pages that share a common set of modules.
JavaScript
840
star
5

example-multipage-shim

Example RequireJS-based project that has multiple pages that share a common set of modules with shim config
JavaScript
382
star
6

require-cs

An AMD loader plugin for CoffeeScript
JavaScript
335
star
7

require-jquery

A RequireJS+jQuery sample project
JavaScript
261
star
8

alameda

AMD loader, like requirejs, but with promises and for modern browsers
JavaScript
195
star
9

example-jquery-shim

Example project that uses jQuery and jQuery plugins via shim config
JavaScript
190
star
10

domReady

An AMD loader plugin for detecting DOM ready
JavaScript
182
star
11

example-jquery-cdn

Example project that uses jQuery and jQuery plugins wrapped as modules
JavaScript
151
star
12

cajon

JavaScript module loader for the browser that can load CommonJS/node and AMD modules
JavaScript
117
star
13

i18n

An AMD loader plugin for loading internationalization/localization string resources
JavaScript
98
star
14

xrayquire

An auxillary script that gives extra info on the use of requirejs in a web page.
JavaScript
74
star
15

example-libglobal

Use AMD modules to develop a JS library that builds to a lib that can be used by "globals only" scripts or as an AMD module
JavaScript
61
star
16

element

An AMD loader plugin for custom elements
JavaScript
56
star
17

requirejs-bower

Repo hold assets for publishing to the bower package manager.
JavaScript
34
star
18

requirejs-npm

Wrappers to allow using RequireJS-related scripts
JavaScript
22
star
19

step

AMD loader plugin that takes a step config to know how to sequential load some files
JavaScript
20
star
20

prim

Promise lib for use inside requirejs-related projects
JavaScript
7
star
21

requirejs-branding

Branding/images/design for RequireJS web site
CSS
6
star
22

browsertests

Standalone browser capability tests to help inform what is possible in a loader
PHP
3
star
23

alameda-prim

The alameda AMD loader that includes private promise shim
JavaScript
3
star
24

requirejs.github.io

requirejs.org site
HTML
2
star
25

requirejs-nuget

Artifact used for pushing to NuGet
JavaScript
2
star