Is it possible to load requirejs under a different name - javascript

I know that for design reasons requirejs doesn't offer a way to load itself in noContext mode, bound to a different variable. Is it possible to do this manually somehow, or does require utilize the specific word "require" to execute its code? I know that it needs to the "require" and "requirejs" global variables to work - is it possible to change these names?
A little context: I am building Chrome extension which needs to load requireJS on a page to load a decent number of modules. However, some pages (upworthy.com and slate.com being 2 prominent examples) have critical functionality already bound to the name "require" (in the case of upworthy, they use requirebin or browserify). So I want to load requireJS without interfering with whatever native functionality is already assigned to require.

The JavaScript execution environment of content scripts are separated from the page, so you should not have any namespace collisions.
If you really need to inject the script in the page, then I strongly recommend to use r.js to generate one single JavaScript file, wrapped in an anonymous self-invoking function. Then, the require variable of your script will not conflict with the one in the page.

Related

Can/will AMD modules load in-between in-line script tags?

For reasons that aren't relevant to the question, my coworker needs to load a script that uses the Universal Module Definition pattern. Our environment usually has an AMD tool loaded, but for more irrelevant reasons, my coworker needs the script to define a global rather than registering a module through AMD. The approach that is currently checked in on their branch is something along the lines of this:
<script>
var backupDefine = define;
define = null;
</script>
<script src="../path/to/some/script/using/UMD.js"></script>
<script>
define = backupDefine;
backupDefine = null;
</script>
My question is: Is this a horrible idea? Is there a guarantee in the way browsers load scripts from script tags that will ensure nothing other than loading the UMD-based script will happen between undefining define and restoring define? We have a very large, very heavily async asset load primarily based around AMD modules, so what I am concerned with is an AMD module attempting to define itself in that intermittent state where define is currently not defined.
So long as UMD.js in no way modifies the scripts in the DOM, those scripts are guaranteed to execute in the order that they're authored in before any asynchronous callbacks that may have been queued before the first script executes.
I see this as a bad idea and spec breaking even if the case where define is always necessary is rare or even non-existent due to <script> load order considering your case. In an AMD environment, define, require and the like should basically be treated as first class keywords since their goal is to help you to remove globals.
Realistically, you're treading into undefined behavior as far as I can tell and writing code that is hard to maintain. You're relying on a tricky case with a spec where you have to undefine something and them immediately redefine it hoping that nothing tried to use it in the mean time. I'd say that that's "unsafe".
If you really need this to happen, I'd comment and document it heavily to make sure a future developer doesn't misunderstand what you're doing. However, I would say the better course of action is to rewrite the UMD.js file so that you export your global your own way. Rhetorically, why are you trying to use UMD if you don't want it to UMD things?
You're writing this module to support AMD through UMD but then you say that you don't want it to be used by AMD. Rewrite the file to just export to the global and avoid messing with define before you accidentally conflict with an additional library that does something tricky with define.

What is exactly define(function(require){...}) in JavaScript

I understand that define is used to define a module, and function is an anonymous function, but what does the argument 'require' in the function hold?
If I write anything in define(function(require){...}), when will this be called? How to give a call to his anonymous function?
Please help, I am new to advanced JS.
This is part of the requireJs api, it's not vanilla JS.
You can see the full docs in here:
http://requirejs.org/docs/api.html#define
"require" in the above example is actually the "require" code, this pattern allows you to require a JS and, than only when loading the JS is completed, load yet another dependency, but do so in the scope of the previously required file.
At large, this pattern allows you to break your app into multiple small JS files, and load them in an async way to speed up the loading process of web pages.
Some would argue that this is all going to be less needed when SPDY and HTTP2 are going to be more widely used. In any case, this is surely promotes a better modularity in the code design.

Asynchronous loading JavaScript functions.

I am building a framework in which I have merged all JavaScript files into one file (minify).
Example:
function A() {} function B() {}
Through minified file i want to load function asynchronous and remove from HTML when its work is done.
Example: load function A when it is required but not function B.
I have seen one framework Require.js but in that it loads JavaScript file asynchronous based on requirement.
Is there any framework which loads JavaScript functions on demand which are defined in same js file.
The downside to concatenation is you get less fine-grained control over what you are including on a given page load. The solution to this is, rather than creating one concatenated file, create layers of functionality that can be included a little more modularly. Thus you don't need all your JS on a page that may only use a few specific functions. This can actually be a win in speed as well, since having just one JS file might not take advantage of the browsers 6 concurrent connections. Moreover, once SPDY is fully adopted, one large file will actually be less performant than more smaller ones (since connections can be reused). Minification will still be important, however.
All that said, it seems you are asking for something a little difficult to pull off. When a browser loads a script, it gets parsed and executed immediately. You can't load the file then... only load part of the file. By concatenating, you are restricting yourself to that large payload.
It is possible to delay execution by wrapping a script in a block comment, then accessing it from the script node and eval()ing it... but that doesn't seem like what you are asking. It can be a useful strategy, though, if you want to preload modules without locking the UI.
That's not how javascript works. When the function's source file is loaded, the function is available in memory. Since the language is interpreted, the functions that are defined would be loaded as soon as the source file was read by the browser.
Your best bet is to use Require.js or something similar if you want to have explicit dependency chains.

closure compiler - keep unused functions and don't rename the undefined

So closure compiler is great but exporting functions and defining externs seems to be too much manual work. Is there a way to tell the compiler that it should not remove any functions and should not rename any undefined functions?
I have 2 major reasons behind this:
If a function or property is not defined in the scope of the javascript document, then it's probably defined in an external file. Therefore, I wouldn't like these to be renamed.
If the function is defined in a given scope but isn't being called within the same scope, then it's probably being called in some external code. Therefore, I would like to keep this function in the file without renaming it.
This way, we could simply compile javascript files without worrying about external libraries and exporting functions that are called from html pages.
It very much sounds like you should run the compiler with the optimization level of SIMPLE_OPTIMIZATIONS. Don't be fooled by the name, as it still fully compiles your code. The main difference is that SIMPLE_OPTIMIZATION will not rename or eliminate dead code in the global scope. This means the requirements of externs and exports are no longer present.
To avoid this, I run the closure compiler on a complete script that is the concatenation of all the scripts of my application. So this is a two-step process :
1 - concatenate all
2 - run the closure compiler
Additionally, you may want (as I often do, due to problems with jquery before v1.8) to run the compiler with compilationLevel="simple".
Concatenation is very important as in general the slowness isn't related to the total size but mainly to the number of requests.
EDIT : of course you have to automate all this. I can provide you an ant task definition if you use ant.

What happens if you use a <script> tag with the same "src" attribute multiple times within a single HTML document?

Although I am almost certain the answer to this question will be browser specific, do any of the browsers define behavior for when multiple <script> tags are used and have the same src attribute?
For instance...
<script src="../js/foo.js"></script>
...
<!-- what happens here? -->
<script src="../js/foo.js"></script>
The reason I ask this question in the first place, is that in my particular case I am using partial views in an ASP.NET MVC application which make use of JQuery. The JQuery JS file(s) are all included in the master template file via script tags. I would prefer to add script tags to the partial view files so that in case they are used outside the context of the master template, they will automatically include all the necessary JS files, and not rely on another view or template to include them. However, I certainly don't want to cause JS files to have to be transferred to the client multiple times, or any other side effects that could negatively impact the user experience.
My thinking right now is that most, if not all, of the major browsers (FF, Safari, IE, Opera) will cache a JS file the first time it is used, and then on subsequent script tags the browser will use the cached copy if available and if it hasn't expired. However, caching behavior can usually be altered through browser configuration, so it doesn't seem too "safe" to rely on any kind of caching behavior.
Will I just have to accept the fact that my partial views are going to have be dependent on other templates or views including the appropriate JS files?
Even if they're cached, you may have problems since the same code will be executed twice. At the very least, this will cause the browser to take more time than necessary. And it may cause errors, since most JavaScript code isn't written to be executed twice. For example, it may attach the same event handlers twice.
Don't output script tags directly in your partials. Create a mechanism to register script files for later inclusion. That mechanism can be responsible for only including files once.
What happens is that JavaScript is feed into the interpreter the moment it is downloaded. In the event of a namespace collision only the variable name, of a given scope, survives to execution. Normally this last only process prevents problems from arising by overwriting functions feed into the interpreter earlier. The problem is that a function defines variable scope, which those variables could be other functions that introduce then other namespace scopes of variables. That is a problem because if functions share the same name value and include different variable definitions then there could be leakage where variables from a function feed into the interpreter early survive even after that function is overwritten, which can then cause expected namespace collisions.
If the exact same file is included twice there should be no problem. The problem occurs when different versions of the same file are included or different files with the same function names are included. Including the same file twice can mean multiple transmissions, which is a waste of bandwidth.
FF 3.5x, Chrome 4x include it only once.
:) IE 8 has two copies (view in Developer Tools > Scripts tab there are two jquery-1.3.2.min.js entries)

Categories

Resources