Coder Social home page Coder Social logo

text's Introduction

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.

text's People

Contributors

braddunbar avatar brettz9 avatar busykai avatar dakota avatar dimitarchristoff avatar gustavnikolaj avatar jrburke avatar mbrocious avatar ngot avatar rafaellyra avatar rphilipp64 avatar smurfix avatar tjvantoll avatar victor-homyakov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

text's Issues

Feature Request for template overrides

I work for NPR and am using RequireJS for a javascript application. We are also using text.js to load in text for templates. We have an issue where we are using some modules that are not within our control and some that we are in control but do not want to fork. So instead we want to override the templates that do exist with our own.

I have come up with some code that will do such a thing and I have forked your plugin to do so.

The code that I changed: https://github.com/nprds/text/commit/9b853658280b279d78f23bb1e495c8518bbdf5b5
I need to note here that the code that I was working off of was text-2.0.3.js and the newest is text-2.0.5+.js

The readme https://github.com/nprds/text/commit/b6a557f26e1dfb0faf8a94a0db07bf5d5d738edf

The only issue that I can think of is, I think, that r.js will save the old template still but this is unconfirmed on my part.

Doesn't honor the `removeCombined` option when optimizing with r.js

I'd love for the text plugin to clean up inlined text modules when optimized. I'd love to take a swing at this (I hacked it locally by caching the file on the node process object and fetch from that cache (unlinking the file once it's cached) but I'm seeing an issue with all require plugins. There's no easy way to add support for these plugins, I haven't looked too closely at the current code in require.js but if there's a possibility to add an hook for this that would be awesome.

Maybe this issue should be solved in require.js core first, and solved here later--but I'd love to hear your thoughts, @jrburke.

Errors not getting thrown in Cordova

Hi everyone,

I'm using the following structure in order to do something depending on whether a template file is found or not:

require ( [text!filename],
function(file) { console.log('success') },
function(err) { console.log('error') } );

This works fine on chrome but, when on a Cordova/Phonegap app, it always returns 'success', even if the file does not exist.

Reusing ajax code

Between plugins and code, I find myself reusing basic ajax code over and over. The best way to avoid this is to use the 'text' plugin as a primary source of the ajax loading code through the api (text.get).

There is also the option of using jQuery, but with the modularity provided by RequireJS, I find it far more economical to require parts of things that might have been provided by jquery (selector / events / ajax / traversing), rather than the whole library. In this way I don't want to be dependent on the entire massive jQuery library as it is not worth the cost of its dependency when there are more efficient ways of loading (as provided by requirejs).

I'm switching back to the text plugin dependency for ajax loading as it is such a common requirement, rewriting this code each time seems pointless, and I don't want to make my own ajax module if it's not in line with overall directions.

I just wanted to check if this is something that is advised or not, because there will be a lot of demand for this in RequireJS. The text plugin itself doesn't make the api clear or document this use case.

plugin not working with Rhino as is

Hey

It's an awesome work you did with require.js and things around.
I'm playing with and SBT plugin for Jasmine running under Rhino with r.js and would like to require some files with the text plugin, but it's not loading. Thing is text plugin's createXhr method is able to return a valid object in my case and tries to load my files with an XHR call instead of the Rhino part of the long if/elseif/elseif stucture around the end of the plugin. If I replace those two parts (it looks like "if node do the node way, elseif rhino do the rhino way, elseif xhr do xhr" in that case) it works ok. Am I missing something? Should I commit it and create a pull request?

Thanks

Jozsef

text.js doesn't work with remote URLs in Node

When loading an external text file with text plugin in Node, it tries to load it as a local file (rather than as a remote file) and I'm getting the next error:

var text = requirejs('text!http://example.com/text.txt');

> Error: ENOENT, no such file or directory 'http://example.com/text.txt'
   at Object.openSync (fs.js:240:18)
   at Object.readFileSync (fs.js:128:15)
   at Object.get (route-to-text-plugin/text.js:230:27)

node errors when not using r.js

i was able to get the text plugin working with requirejs as a node module, but it took a bit of modification. is the text plugin intended to work via node, without using r.js? if so, what could i be doing wrong? if not, what can we do to get real npm support?

below are errors and my resolutions...

Error: Calling node's require("text") failed with error: Error: Cannot find module 'text'
# create text in node_modules

Error: Calling node's require("text") failed with error: ReferenceError: define is not defined
# add amdefine compatibility

Error: Calling node's require("text") failed with error: TypeError: Object #<Module> has no method 'config'
# change module.config() to {}

Error: Object function has no method 'nodeRequire'
# change require.nodeRequire to require

Publish to npm

We're pulling this down with "text": "requirejs/text" in our package.json, but that's rather suboptimal.

X-Requested-With "XMLHttpRequest"

Can be this header added to request
By this method server can determine not to redirect to login page, when session is expired but simply to return 401

jQuery do this in his jQuery.ajaxTransport

        text.get = function (url, callback, errback) {
            var xhr = text.createXhr();
            xhr.open('GET', url, true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Resoving parent directory failed

Fails in such cases:

require("text!../cirru/table.cr")

But works when I wrote this into config.paths.
Not sure but this one leads to wrong url too:

require("text!./cirru/table.cr")

Load timeout for modules: text!filename.html_unnormalized2_unnormalized6

Uncaught Error: Load timeout for modules: text!Template.File1.html_unnormalized2_unnormalized6, text!Template.File2.html_unnormalized3_unnormalized7

http://requirejs.org/docs/errors.html#timeout require.js:192
makeError require.js:192
checkLoaded require.js:754
(anonymous function)

For a long time in development where our files aren't built (we're loading around 451), we get above error. File1 and File2 are the first templates in the stack being called.

This is an intermittent error that fluctuates in frequency.

I can't quite pin it on text except that it only errors out on the html files being loaded with text plugin every time.

I apologize if I've missed this in resolved issues with Require or text plugin.

using the text plugin by the optimizer

Hello,

I am using the text plugin in the optimizer (using grunt-contrib-requirejs). It works well, but I have to place by hand the text.js plugin in the correct path, for example in the same directory as the Gruntfile.js. Is there any better way to make requirejs "aware" of the text plugin so that I don't need to place it by hand for every project?

best regards.

how to override a load method ?

I want to override a load method such that I can tamper with the url. I tried writing my code inside plugin directly, it works. I want to take out this code. I tried following way :

requirejs.config({
config: {
text: {
load: function (name, req, onLoad, config) {

It doesn't work. How to do it ?

enable npm support

tl,dr
neither
npm install ..
nor

{
   "dependencies": {
      "text": "https://github.com/requirejs/text"
   }
}

works

The project contains a package.json file but neither can i get it on npm nor can i load it by giving npm the repository url (npm install crashes when i do so)

Allow changing location of the text.js file.

Quoting the README: "Download the plugin and put it in the app's baseUrl directory."

Please allow to change this setting. I don't want to clutter my root directory with plugins, no matter how amazing they are.

Thank you for the great job.

IE8 Object doesn't support this property or method

Internet explorer 9 running in Compatibility mode for IE8.

Creates XMLHttpRequest even when not needed(all resoruces are packed and included) and fails on first page load. page reload fixes the issue. new XMLHttpRequest() causes error "Object doesn't support this property or method"

related to: #14

current workaround in production to get things working:
requirejs.config({
....
config: {
text: {
createXhr: function () {
// IE8 override :S
return {};
}

XHR Caching

need to do set the header, but heres an ez/lzy workaround

requirejs.config({ config: { text: { onXhr: function (xhr, url) { url = url + Math.random(); } } } });

Windows Phone 8 and cordova problem

Hi,
there is a problem with text plugin. It doesn't load text resources and gives 404 error. It is any chance to override a XHR restrictions on WP?

text.js doesn't work on first load in IE 8

I am using backbone and underscore for my app. I am using version 2.0.1 of require.js and version 2.0.0 of text.js.

When i navigate to the app by going to index.html i get the following errors:

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
Timestamp: Thu, 9 Aug 2012 18:50:11 UTC

Message: Object doesn't support this property or method
Line: 57
Char: 17
Code: 0
URI: http://192.168.248.111:8080/in/js/libs/text.js

Message: Load timeout for modules: text!templates/paystubContainer.html_unnormalized2,text!templates/header.html_unnormalized3,text!templates/addCompany.html_unnormalized4,text!templates/large-check.html_unnormalized5,text!templates/large-check.html_unnormalized6,text!templates/main.html_unnormalized7,text!templates/calendar.html_unnormalized8,text!templates/small-check.html_unnormalized9
http://requirejs.org/docs/errors.html#timeout
Line: 1756
Char: 9
Code: 0
URI: http://192.168.248.111:8080/in/js/libs/require-jquery.js

ALSO the error seems to go away if i refresh the page. On the refresh the app seems to work just fine.

Requiring a template with the text plugin causes the template to be evaluated

This is driving me crazy. Can you please tell me what, if anything, I am doing wrong? The following...

require(['text!/static/js/fool/ceo.hb.html'], function (hb) {
});

...results in the following error...

invalid object initializer
<p>My name is {{name}}!</p>
- - - - - - - -^

It seems like RequireJS is trying to evaluate the template file, resulting in a JavaScript error.

I'm using requirejs-jquery.js with RequireJS 2.0.2 (and jQuery 1.7.2) and the text.js plugin v2.0.0 (found here: https://raw.github.com/requirejs/text/latest/text.js). I have verified that the text.js file is indeed getting loaded.

Extend text.get to be able to receieve request headers

the text plugin is being used by the json plugin (correctly or not). unfortunately, some restful servers depend on the accept header to determine the content-type of the response and may default to say, XML.

The issue is that the text plugin exposes no way to set request headers at present.

I know you can hack via config: { text: { onXhr: function(xhr){ ... } } } but the json plugin has no direct access to that. It will be much more useful to change text.get to accept an optional 4th argument headers (obj) and set these on the xhr instance before the open.

A quick hack that worked:

        text.get = function (url, callback, errback, headers) {
            var xhr = text.createXhr(), header;
            xhr.open('GET', url, true);

            if (headers && headers === Object(headers)) {
                for (header in headers) {
                    if (headers.hasOwnProperty(header)) {
                        xhr.setRequestHeader(header.toLowerCase(), headers[header]);
                    }
                }
            }
   ...

and in json.js just pass as 4th argument.

{
    Accept: 'application/json'
}

I'd do a pull request but I cannot figure if this is the best API to do it or how to mimic the same for rhino file stream.

Configurable Filters (e.g. strip)

I have some super hacky code that implements this, however, I want to get some feedback before going full on with it and submitting a pull request. Here goes...

I was starting to use the plugin to load templates for a Backbone app. It works super great, but I have to manually compile the templates in each module I depend on them. I'm specifically using Handlebars and I found another plugin that is built specifically for such a task, however, it appears to replicate a lot of the code that this plugin uses and really, all I need the text plugin to do more than it does is apply Handlebars.compile before returning the content. I started expanding on the idea of "!strip" in such a way that you could apply an arbitrary amount of filters like so:

require(['text!some_file.html!strip!noop!handlebars'], function(template) { });

and they could be configurable like so:

require.config({
  config: {
    text: {
      filters: {
        noop: function(content) { return content; },
        handlebars: function(content, next) {
          require(['handlebars'], function(Handlebars) { next(Handlebars.compile(content)); });
        }
      }
    }
  }
}

A filter function would take 2 arguments: the content and a callback for moving to the next filter. It could either return the filtered content directly or use the callback in the case that async work is required to apply the filter.

Like I said, I have some code that works, I'm looking for a little guidance on whether something like this is desirable or a good idea.

Dynamic text! plugin paths?

I realize that the require() call must use string literals for determining the path of the file to load, but is there ANY way to create a scenario where the path can be converted to the desired string literal prior to the text! call? Possibly in the text config onXhr or createXhr handlers? For instance, can I change the url in the onXhr function such that it uses an altered path? And if so, would this alteration still happen during the r.js optimizer process?

What I am trying to do is alter the text! plugin path to use a phone or tablet version of my HTML templates based on user agent detection. Pretty sure I can create a build scenario to create separate builds and load the appropriate file per device, but I am thinking more about the development environment when the text plugin is actually making the XHR call on the fly.

Not sure if there is a better way to do this or not...thinking there has to be some way though..hoping anyway :) Thx in advance for any ideas on this issue.

Customize the createXhr function

What would you think about allowing the user to specify a createXhr function in the module().config that would be responsible for providing a valid xhr?

The use case I'm specifically thinking of is by using document.domain and iframes to provide donor XHRs, you can support cross domain ajax at least within top level domains without special headers, negotiations, or any server config. This could be useful when used in something like an intranet. This method works at least as far back at IE6 as well I believe.

Unexpected token error '<'

I have text.js located in the same directory as requirejs so there are no issues loading the plugin. Here's the top of my data-main requirejs script.

require.config({
    paths: {
        handlebars: 'lib/handlebars',
    },
    shim: {
        'handlebars': {
            exports: 'Handlebars',
        }
    }
});
require([
    'handlebars',
    'text!templates/user_view',
     ], 
    function(handlebars, template_source) {
        console.log(handlebars);
            console.log(template_source);

Both the console logs print undefined (the first is fine, because Handlebars is callable, I verified). Clearly the template is not being read somehow. The error in the browser is 'Uncaught SyntaxError: Unexpected token <' . Checking in the Chrome dev tab, text.js and the template are loaded by requirejs. The template starts out with a simple

tag, nothing wrong with that.

Strange part -> There are no problems reading the templates using Handlebars when running my Django project locally. In production, the only difference is that static files are read from Amazon S3.

Can you please advise soon? Anyone with theories or workarounds I would very much appreciate them!

I need to make this work. My workaround is to copy the template into a string, remove newlines, and assign directly to a Javascript variable (i.e. workaround is to not load templates) which does work.

module.config is not a function

When text.js sets the masterConfig variable I am getting "module.config is not a function"

pulling my hair out trying to figure out why.

Allow text.js to pull in a single html file as a jQuery object instead of only text

Normally if I have a bunch of templates in the DOM I'd be able to pluck them out by referencing the script id tag e.g.

$('#js-comment-delete-tmpl').html();
$('#js-comment-add-tmpl').html();

Because the text.js plugin reads in the html file that the templates are in as text, I can't exactly put all my say comment namespaced templates into e.g. /scripts/templates/comments.html because it'll just be one long string of text. Unless I do some weird regex matching (which would be expensive), I have to put all my comment namespaced templates into individual files. So I have to do this instead:

/scripts/templates/comments/add.html
/scripts/tempates/comments/delete.html

You can see my frustration when I have multiple templates for one common view (in this example a comment view). Ideally I'd be able to just put them all into one html file

In /scripts/templates/comments.html:
<script type="text/template" id="js-comment-delete-tmpl"></script>

<script type="text/template" id="js-comment-add-tmpl">/script>`

etc. to prevent fragmentation.

So to get some kind of namespacing from putting them all into a common file (e.g scripts/templates/comments.js), I just put them into a CommentsTemplate object

define(function() {
    commentTemplates = {};

    commentTemplates.reply = [
  '<div class="js-comment-reply-tmpl comment_container">',
    '<div class="comment_reply">',
      '<textarea class="js-comment-textarea" name="comment"></textarea>',
      '<div class="comment_post_button">',
        '<input class="js-comment-reply btn btn_small btn_primary" data-action="reply" type="submit" value="Reply to {{username}}">',
        '<button class="js-comment-reply-show btn btn_small" data-action="replyShow">Cancel</button>',
      '</div>',
    '</div>',
  '</div>'
    ].join('\n');

This works alright, but if I want to put some conditional logic into my templates that will work with underscore's built in templating, I can't.

It'd be nice to be able to load my html file but wrap it in a jQuery object instead of just a string.

error loading templates with cordova

Hello Everyone,I've been trying to develop an app in phonegap in Windows phone 8. Everything works fine in iOS and Android, but I'm getting a really strange error message.

ERROR: failed to InvokeMethodNamed :: readResourceAsText on Object :: File
CommandString : DebugConsole/log/DebugConsole1223202439/"Error in error callback: File1223202438 = Error: js/../templates/home/home.html HTTP status: 404"
Log:["Error in error callback: File1223202438 = Error: js/../templates/home/home.html HTTP status: 404","DebugConsole1223202439"]
The thread 0xea8 has exited with code 259 (0x103).

so i'm used BackboneJs + Jquerymob + require and textjs plugin the problem is found at int start = int.Parse(optStrings[2]); in file plugin of phonegap File.cs and the content of pathToResource ="js/../templates/home/home.html" loading template that's why I think that this is the problem.
Do you guys know anything about it? i'm sorry for my english
thanks.

Strange behavior when not specifying file extesion

Hi,

I noticed this strange behavior when not specifying the file extension.

Basically what happens if I don't have a file extension when loading a template is that it completely makes the text plugin go wrong parsing the module name and ignores the paths in the requirejs config.

F.e:

require.config({
  ...
  paths: {
    'tmpl': 'templates'
  }
});

and I have the template 'result' inside the templates dir.
the following paths will not work:

  1. text!tmpl/result
  2. text!templates/result

The first will be resolved as a normal folder named tmpl (instead of paths config)
Both the first and the second will be parsed with a dot before the directory: '.templates/result' , '.tmpl/result'
Putting an extra / after the text! resolves the dot issue e.g. ./templates/result

I dunno if it's a bug or was designed this way (requiring an extension)
Didn't see any issue similar to this.

Thanks!!

Edit:
Extension doesn't exist in the real file as well.

Loading text files with requires.js fails in Firefox: “AccessControlException”

Hello,

i have also have a question on stackoverflow running regarding my issue:
http://stackoverflow.com/questions/11881411/loading-text-files-with-requires-js-fails-in-firefox-accesscontrolexception

I am using requires.js 2.0. I have the following simplified use case:

my HTML file:

<!DOCTYPE HTML>
<html>
<head>
    <title></title>
    <script type="text/javascript" data-main="apptest.js" src="../_js/libs/require/require.js"></script>
</head>
<body>

</body>
</html>

And then in apptest.js:

requirejs.config({
    paths: {
        'text': '../_js/libs/require/text'
    }
});

requirejs(
    ['text!boxes.html'],

    function (Boxes) {
        alert("done");
    }
);

Ok, so it doesn't really do much, but enough to make my point. Only in Firefox (14.0.1) i get an exception "uncaught exception: java.security.AccessControlException: access denied (java.io.FilePermission .\boxes.html read)".

So, require.js successfully loaded the text plugin, but fails loading my html file, which i want to use as a template later on. In Google Chrome and even IE9 it works just fine. I am on Windows 7.

I am running this on a local webserver, so no file://... requests here.

I have checked, if i have any special permissions set on the html file, but have not found anything suspicious.

Anyone have an idea?

Update: Running the test in Firefox 13.0.1 does actually work for me without errors. So could it be, that this is a bug, that has been introduced in firefox 14?

Use text plugin w/ CommonJS syntax

I'd like to use this plugin w/ commonJS syntax, so instead of the example y'all have:

require(["some/module", "text!some/module.html"],
    function(module, html) {
        //my code
    }
);

I'd like to do the following using the "synchronous pre-loading" method via commonJS syntax:

var someModule = require("some/module");
var someTemplate = require("text!some/module.html");

function(module, html) {
  //my code
}(someModule, someTemplate);

However, when I try to implement this, requireJS throws me the following error:
"Uncaught Error: Script error for: some/module.html"

I am sure all the paths are right, so is this just something that's not supported in the text plugin, or is there a way to get it working using the commonJS method?

text.js throws "file not found" errors from time to time

Hi,

first of all: thank you for your great work on this plugin, this is one of the reasons I really like to work with RequireJS :)

However, I've been facing a weird issue with text.js lately.
Although, it succeeds most of the time in downloading my templates, it fails like once out of 6 fresh page loads.

You can easily reproduce the problem:

  1. cd /where/you/want
  2. git clone git://github.com/LateralThoughts/lateralthoughts.github.com.git
  3. git checkout templatization
  4. python -m SimpleHTTPServer 8000
  5. myFavouriteBrowser http://localhost:8000
  6. refresh several times till you see errors in your developer console

I did only work on the index.html file, the other static files do not depend on RequireJS yet.

Do you have any idea what's wrong?
Thanks in advance!

Florent

P.S.: by the way, my attempt to create an animation (here, hardcoding body opacity, later reset by /js/modules/rssReader.js) feels very hacky. Is there an elegant way to stop an animation when all external resources are fetched by text.js?

textjs doesn't work with dynamic path

I use requirejs with text plugin to load template for my app, when i wrote:

var template = require('text!/assets/mytemplate.html');

it's ok. But i change my code to:

var path = 'text!/assets/mytemplate.html';
var template = require(path);

it doesn't work :(. Anyone can help or give me solution.

// sorry about my english

Alternative text including approach

Hi, I would like to propose an enhancement. I think the most common need for including text dependencies is because of templating code. This code could be hosted on a different static server, like the whole application, this is what makes requirejs so powerful. But here the troubles about cross domain asynchronous requests arises.

So, an alternative to CORS and .js loading could be the one adopted by handlebars, that is, to include a script tag with an user defined type.

Uncaught Error: Script error for: text

I get the above error in Chrome. I get this error in Safari:
"TypeError: 'undefined' is not an object (evaluating 'e.normalize')"

Here is the code causing the problem:

require(["scripts/text.js", "text!templates/template.html"], function() { console.log(arguments); });

Even without the console.log line, it still breaks. I've tried loading the text! after text.js has loaded, and it made no difference.

using an object to define dependency:variable pairs

Hey,

Was wondering, Is it a bad idea to support a different kind of, non-breaking, dependency definition?

Having something like:

define(
'moduleName',

{
'lodash' : '_',
'zepto' : '$',
'backbone' : 'Backbone'
},

function callback () {
// code goes here, _, Backbone, $ are available
}

)

if the dependencies are defined as an object instd of an array: exports = callback.apply( context, [ argsArray ] ).

Dunno, what do you think?

cahcing

HI,
I have noticed that the page is loading as it is with no cache after the .html
I have to delete the cache on every change.
Have you considered adding a ?cahce=xxxxx.
(I know this isn't a 100% cache fix but it will help)
Or any other caching solution would be great (in case I am missing something)

Thanks,
Yaron

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.