1

I've been using RequireJS and it works perfectly. I use a lot of "window.document" to manipulate different DOM elements, but when I try to optimize it with r.js i get a ReferenceError: window is not defined which only happens with r.js.

Here is a minimal example of code that reproduces the issue:

index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body >
<div id="commentbox">

</div>
<script data-main="code/main" src="code/require.js"></script>
</body>
</html>

main.js:

 require(["roomManager"], function (roomManager){
 return {

 }
 });

roomManager.js:

define(["commentManager"], function(commentManager){
    var commentHand = new commentManager.commentHand();
    commentHand.init();


    return{

    }
});

commentManager.js:

define([], function(){
    function commManager(getDisplayIdVariable){
        var messagebox = window.document.getElementById("commentbox");

        this.init = function(){
            messagebox.innerHTML = "hi!";
        }
    }
return{
        commentHand : commManager
}
});

This version works correctly without r.js but when I try to compile it by running r.js main.js. I get this:

var messagebox = window.document.getElementById("commentbox);


ReferenceError: window is not defined
         at new new commManager
0

2 Answers 2

2

You cannot just do r.js main.js.

For one thing, you have to specify -o so that r.js performs the optimization. (r.js can be used for other things.)

You also have to pass configuration to r.js, either in a file, or on the command line. One possibility for you would be:

r.js -o name=main out=built.js

I've tried this with the code you show in your question and I get no errors.

I strongly suggest going over this documentation for r.js.

Sign up to request clarification or add additional context in comments.

Comments

0

if your code is optional you can use

 if (typeof window !== 'undefined') { 
       // Inside browser
} 
{
  // outside browser
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.