particles.js and window is not defined

蓝咒 提交于 2019-12-11 16:07:25

问题


When I start my app using node app.js then then I get the following error:

/home/ubuntu/workspace/nodeapp/node_modules/particles.js/particles.js:1429
window.requestAnimFrame = (function(){
^

ReferenceError: window is not defined
    at Object.<anonymous> (/home/ubuntu/workspace/nodeapp/node_modules/particles.js/particles.js:1429:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/ubuntu/workspace/nodeapp/app.js:5:19)
    at Module._compile (module.js:570:32)

I'm trying to use particles.js as my background, I installed the package with npm. Here what my app.js looks like:

var express = require("express")
var app = express()
var request = require("request")
var PythonShell = require('python-shell');
var particlesJS = require("particles.js")
app.set("view engine", "ejs")
app.engine('html', require('ejs').renderFile);
app.use(express.static("public")); 

particlesJS.load('particles-js', 'assets/particles.json', function() {
  console.log('callback - particles.js config loaded');
});



app.get("/", function(req, res){
    res.render("main")
})



app.listen(process.env.PORT, process.env.IP, function(){
    console.log("Movie App has started!!!");
})

And Im storing particles.json inside assets folder. The html looks like this:

<html>
    <head>
        <div id="particles-js"></div>
        <script src="particles.js"></script>
        <title>MYMDB</title>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.css">
        <link rel="stylesheet" type="text/css" href="/stylesheets/app.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
    </body>
</html>      

回答1:


This is because window is a browser object, and it looks like you're trying to load particle.js on the server side, in node.

Try moving your particlesJS.load call into the browser.

From their npm page:

Initialize the plugin on the window.onload event.

window.onload = function() {
  Particles.init({
    selector: '.background'
  });
};


来源:https://stackoverflow.com/questions/47125954/particles-js-and-window-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!