Bad practice to invoke RemoteAction on page load? From Static Resource?

I’m working with a page that is a container for a single page app.

<apex:page>
    <div id="root"></div>
    <script src="{!URLFOR($Resource.javascriptResource)}"></script>
</apex:page>

In the beginning of my resource, I’m invoking a @RemoteAction:

Visualforce.remoting.Manager.invokeAction("Controller.getOptions", ...args, function(result, event) {
    //do stuff with the result.
});

I’ve noticed that during development, if I load the page, modify the resource and save it to server, and then reload the page, the Visualforce global is undefined. If I then reload once again, it is properly defined. Does anyone know why? Does this have any potential to affect users in production or would this only occur in development as I described?

Answer

I think it is perfectly fine practice to use @RemoteAction to load your application, but you should not count on variables like Visualforce or any merge fields to work from within a Static Resource. They are easier if you reference the method this way (you do not need any inheritance model to make such a reference). What I have done in the past is load the RemoteAction into an object I can then pass to my application. With angular, for instance, I can do:

(function (a) {
    "use strict";
    a.module("myApp", []);
    a.constant("mergeValues", {
        "myRemoteAction": MyController.action
    };
})(angular)

There are many ways you can pass your action to your application, and this is just one example. The main takeaway is that you should pass the function. Another option if you are not using any framework another option may be to create a namespace.

(function (w) {
    "use strict";
    w.myNamespace = w.myNamespace || {}
    w.myNamespace.action = MyController.action
    Object.freeze(w.myNamespace);
})(window);

Then in your static resource, you can do:

w.myNamespace.action(params, callback);

Attribution
Source : Link , Question Author : Matt Thomas , Answer Author : Adrian Larson

Leave a Comment