Require.js (almond.js) Timing Off - requirejs

I'm trying to use Almond.js and the Require.js optimizer to make a standalone file that can be used without Require.js. I've been able to successfully compile the file, and all the code runs, but there's one problem: the code executes in the wrong order.
Let's say my main file (the one that's in the include= option passed to the optimizer) has the following:
console.log('outside');
require(['someFile'], function(someModule) {
console.log('inside');
window.foo = someModule.rightValue;
});
and then out in my HTML I have:
<script src="myCompiledFile.js"></script>
<script>
console.log('out in the HTML');
</script>
Since I'm using almond.js and a compiled file (and therefore there's no file loading going on) I would expect to get the output:
outside
inside
out in the HTML
However, it turns out there's still some asynchronicity going on, because what I actually see is:
outside
out in the HTML
inside
and if I try to check window.foo from the HTML it's not there.
So, my question is, how can I get the code to be more like a normal/synchronous JS file, which runs all its code first before passing things on to the next script block? I can't exactly tell my users "wrap all your code in a window.setTimeout".

By default Almond replicates the timing semantics of RequireJS' require call. Since require is asynchronous in RequireJS, it is also asynchronous in Almond. This can be readily observed in the source: Almond uses a setTimeout to schedule the execution of a module even though it could execute it right away. It makes sense because in the general case developers don't expect that the code they've crafted to work asynchronously will suddenly become synchronous just because they are using Almond. It does not matter in every project but in a project where the UI (for instance) should be refreshed in a certain order, changing the timing semantics could break the code.
Two options:
As the comment just before the setTimeout states, using require('id') works globally with Almond. This is because once your bundle is loaded, everything is guaranteed to have been loaded (since Almond does not load dynamically).
There's also a way to call require with extra arguments. If the fourth argument is true, the call is going to be synchronous:
require(['someFile'], function(someModule) {
console.log('inside');
window.foo = someModule.rightValue;
}, undefined, true);
This can be ascertained by reading the code of Almond. There's no documentation I could find on forceSync (that's the name of the parameter in question) but some bug reports mention it and I've not seen any comment there that it is meant to be a private functionality.

Related

Cant figure out what these errors happening on my webstore? Anyone help, posting the error content

enter image description here
No idea whats going with these errors code, i dont understand why is it saying anonymous and its giving me security concerns
Strictly speaking, those are warnings (not errors). Nothing is broken, but some things may be running sub-optimally. The alerts are noting that the code on your site is preloading a number of assets but not using them right away. This may indicate that your site is unnecessarily using priority resources to bring those resources in.
Beneath the warning message, you are seeing what is known as a "call stack" - it's the chain of functions that have been called to get to the point that resulted in that warning message. There are two kinds of functions in Javascript: named functions and anonymous functions.
Named functions are what you might normally think of as a function. You declare it with something like:
function doSomething(parameter){
// Some awesome code here
}
And later call it as:
doSomething(some_input);
However, in Javascript we can also create un-named, aka anonymous, functions in-line. This is often done for 'callback' functions, or functions that serve as a part B to the main function's part A, especially when part A does something asynchronously.
For example, if we want to fetch a file and then do something with it once it loads, we would make an asynchronous file call and then run our callback function once it loads. If we're using a library like jQuery as a helper to make that call, our code might look something like this:
function getPageAndDoStuff(url, callback){
jQuery.get(url, callback)
}
// We can declare a named function to do our stuff...
function justLogIt(html){
console.log(html);
}
getPageAndDoStuff('/cart', justLogIt);
Alternatively:
// We can just declare an inline anonymous function to do that
getPageAndDoStuff('/cart', function(html){
console.log(html);
})
The latter is a common design pattern for many types of tasks, but you'll note that the function we pass around doesn't have a name. When something happens and we look at the call stack to see the order of functions that have been called to get us to that point, what name would we print? Each unnamed function in our chain is simply called "(anonymous)"
Going back to your posted image, there is nothing in what you're showing that indicates a cause for serious concern. The script file 'rocket-loader' is possibly pre-loading a few assets that it doesn't need to, so you may be able to boost your site's performance by tweaking whatever parameters 'rocket-loader' uses to be more selective in what you are pre-loading.

Immediately invoked function expression isn't executed on second require

Here is a sample code to make it more clear.
This is my module:
module.exports = ((parameter) => {
console.log(parameter);
})('some value');
mymodule is actually the main server file and thus has to be executed immediately.
My unit tests in test suite require my module but the immediately invoked function expression is executed only first time.
require('./mymodule');
require('./mymodule');
How can I make this run every time ?
You can invalidate the cache that Node maintains:
require('./mymodule');
delete require.cache[require.resolve('./mymodule')]
require('./mymodule');
You are probably better off though with exporting the function and calling it when needed, instead of only exporting the result.
From nodejs docs:
Multiple calls to require('foo') may not cause the module code to be
executed multiple times. This is an important feature. With it,
"partially done" objects can be returned, thus allowing transitive
dependencies to be loaded even when they would cause cycles.
https://nodejs.org/docs/v0.4.12/api/modules.html#caching
If you want to have a module execute code multiple times, then export a function, and call that function.

Provide jquery explcitly with requirejs

I'm working on a page that is in progress of transitioning from script tags to require.js. This means that some dependencies are loaded via <script> and others via require.
For the most part, in my require modules I can still treat global scripts as modoules (and thereby help the transition) by doing something like this in my bootstrapping file
define('Globalize', Globalize);
define('knockout', ko);
However this won't work with jQuery since it is a function and require will try to invoke it as a callback. Is there a way to tell require "yes this is a function but return it directly, don't try to invoke it"?
And yeah, I can't just load jquery twice because I've got bootstrap modifying it, and things depending on bootstrap
Oh...
define('jquery', function() { return window.jQuery});
duh.

Cannot set breakpoint inside function when using require inside closure

Using node-inspector, I'm unable to set breakpoint in the following node.js code. (Content of main.js)
(function() {
require('underscore');
var doSomething = function(callback) {
callback('doSomething Finished');
}
doSomething(function(x) {
console.log(x);
});
}).call(this);
I can easily set a breakpoint on line 2, line 4 or line 8, however no matter how hard I try the debugger won't let me set a break point on line 5 or line 9. To be clear, I'm using the following commands to run node-inspector
node --debug-brk main.js
node-inspector
I also tried to debug in web storm, however the issue persists. If I remove the line require('underscore');, then the problem immediately goes away and I'm able to set break point inside function body again. The problem also goes away if I remove the outermost closure function. It seems that the interaction between require and file level closure is screwing up the node debugging functionality. Has anyone experienced this problem themselves and / or knows any workarounds to be able to break inside function body?
EDIT: My node js version
Tony:~ $ node --version
v0.10.12
Tony:~ $
I ran exactly into the same issue with the same setup.
I've added a breakpoint after the definition of the target-function (that was the only place i could actually add a breakpoint). When the debugger reached that breakpoint and the function was actually defined, i was able to add breakpoints to the actual target-function...
This may not be the answer that you want to hear as it doesn't explain why you can't set any breakpoints, but I would simply remove your require statement from the closure and place it top-level. I would go even further and recommend that you don't use a closure like the one above at all.
The reason is that node uses its own module system, and unlike Javascript in the browser, declaring variables top-level does not pollute the global namespace. This is where require(...) comes in. So, you gain nothing by wrapping your code in an immediately invoked function (unless of course you want your module to be able to run both client side and server side).
I would guess that the reason that you are not able to set any breakpoints is that the V8 runtime is recognizing an unnecessary closure and then optimizing your code for you. The rewritten code may not have the correct source mapping and so breakpoints cannot be set.
So, two suggestions:
require calls are not like regular statements. They are more similar to import statements in Java and are handled specially by the compiler. They should always be top-level in a node file.
No need to wrap your code in an anonymous function when in Node.

Perform GM_xmlhttpRequest() from eval

I have a little Greasemonkey script that communicates with a servlet on (my) server. The servlet is sending back JavaScript code, which I eval() in the onload handler of the GM_xmlhttpRequest.
So far, all is working fine. Now, I'd like to use send another GM_xmlhttpRequest from within that eval()ed code. and here I'm stuck. I do not see any error, but all GM_* functions appear not to be working from within the eval(responsetext).
If I hard code the GM_xmlhttpRequest in the onload handler (no eval()), it is working fine.
It is possible to work around this problem, you can call GM_* functions with setTimeout set to 0 from eval'ed code. Try something like:
function myFunction()
{
GMXmlHttpRequest(...)
}
eval('setTimeout(myFunction, 0)');
A better solution is to extend Function.prototype with a function called safeCall that does this for you. Whenever you have any eval'ed code that will call into GM_* functions you'll need to have safeCall somewhere in that call chain.
Greasemonkey (GM) is hosting the user script, which means that it can add functions and objects to the user script, when you call eval() the script runs unhosted (the vanilla JavaScript is running it) and you don't get the GM API inside of it.
There is another solution. I have the similar problem, I don't want to put all my logic in user script, because if I change them, user need to update them by themselves. So what I want to do is separating the main logic from loading logic, the main logic will be loaded at beginning by the user script and eval them.
So I made a function "sendRequest", which is a wrapper of GM_xmlhttpRequest(), I need it anyway, because the method, server url and onError callback are always same for my application, so I just put them into my "sendRequest" function to make the xmlhttprequest simple.
In the main logic javascript code, which is loaded from server, there is no greasemonkey function call at all. If I want to for example communicate with server, I will call sendRequest instead. It works.

Resources