0

I'm new to Meteor.JS and trying to use a script on the server. When I needed a script on the client, I just used jQuery's $.getScript(my-script.js) to load it, but on the server, I get a $ is not defined error, presumably because jQuery isn't loaded on the server. How can I achieve a similar result server-side to the $.getScript() call?

Ruben Martinez Jr.
  • 3,199
  • 5
  • 42
  • 76
  • 1
    can you explain your use case a bit more? why is it not sufficient to just add the file into your project folder? Do you only know at run-time which script you want to load? – Christian Fritz Nov 10 '14 at 04:58
  • ^You are correct, I did not realize I could do this and achieve the same effect. However, I must add that I did (oddly) have to change some of the variable declarations in the script I was loading to be global. Consider leaving as answer? – Ruben Martinez Jr. Nov 10 '14 at 07:58

3 Answers3

3

You don't need to load external scripts manually, you can just add them as files into your project folder. All files in your folders will be loaded by meteor. See the Namespacing section of the documentation for directions on how to make definitions available globally rather than just internally to the script.:

// File Scope. This variable will be visible only inside this
// one file. Other files in this app or package won't see it.
var alicePerson = {name: "alice"};

// Package Scope. This variable is visible to every file inside
// of this package or app. The difference is that 'var' is
// omitted.
bobPerson = {name: "bob"};
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
0

I wouldn't advice the process, especially on the server. This exposes you to lots of risks. The .getScript method uses eval which creates a remote code execution vulnerability on your app.

Nonetheless you can use the http package

meteor add http

Then you can retrieve the script & execute it:

var jsCode = HTTP.get("<full url>").content;
eval(jsCode);
Tarang
  • 75,157
  • 39
  • 215
  • 276
0

If you're using a third party script, the best practice is to create a package to wrap it. In the package you've to export the global variables of the package: api.export('GlobalVariable')

If you're adding your script in the server folder, don't use var, otherwise it will stay only global to the file scope.

jQuery doesn't exists on the server and for a good reason: you need a DOM to use it. You can use phantomjs to do it: Server-side jquery

Not all code runs on client and server.

Community
  • 1
  • 1
Mário
  • 1,603
  • 14
  • 24