0

I'm getting an error TypeError: document.body is null in javascript.

And the solution is found here. But the problem is that how can I load the specific javascript file(where the error come from) after <body>? Or just add a window.onload = function() to this file?

and especially, how to tell the path of the javascript file to the app?

I only know how to include every file into the application.js, which would trigger before the <body> load

Community
  • 1
  • 1
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206
  • Have you tried adding `window.onload` as per the suggestion? Did it not work? As for the paths - you can use relative paths (e.g. `../scripts`) or absolute (e.g. `http://...`). – maksimov Jul 22 '13 at 07:46
  • Its even better if u place your script before the closing body tag [

    ](http://stackoverflow.com/questions/7751514/javascript-in-head-or-just-before-body)

    – DarkBee Jul 22 '13 at 07:52
  • well,I know what you mean @maksimov. The problem is that relative path in Rails seems quite complicated, and does not work that way – ZK Zhao Jul 22 '13 at 07:56
  • You can always modify the DOM using jQuery. Instead of onload, you use $(function(){ /* script here * / }); and in the place of /* script here * / you put $('body').append($("This is my span")); dont forget to include jquery.js – Anders Lindén Jul 22 '13 at 07:57

1 Answers1

1

Since you mention application.js I assume you're using Rails? In that case, use javascript_include_tag to include your file in the application.html.erb just before the closing </body> tag.

fiskeben
  • 3,395
  • 4
  • 31
  • 35
  • Yes, I type Rails in the title but then it get edited. I thought about the solution. It certainly would work. But we do not need every file to load after the `` tag, don't we? (I guess maybe there are some performance difference) And that's why I'm asking if I can just put a specific js after `` – ZK Zhao Jul 22 '13 at 08:01
  • If your script isn't crucial to initialization of your page (for instance a script that contains onclick handlers, form submit stuff etc) then you should put it at the end of your document. This way the browser will render your page first and it will feel at little faster to the user. – fiskeben Jul 22 '13 at 08:06
  • Well....I just tried the solution. It results another problem, seems like I cannot just put `application.js` before the `<\body>`. Anything I can do to put the specific js file there? I guess it would be something like`javascript_include_tag my_specific_js_file`? – ZK Zhao Jul 22 '13 at 08:12
  • `= javascript_include_tag('yourfile.js'); ?>` should do, yes. – fiskeben Jul 22 '13 at 08:18
  • And where can I put the `yourfile.js`? And how to tell the app its path?(It may be in `lib` or in `assets`) – ZK Zhao Jul 22 '13 at 08:21
  • Take a look at the [documentation](http://apidock.com/rails/ActionView/Helpers/AssetTagHelper/javascript_include_tag) on how to use `javascript_include_tag`. – fiskeben Jul 22 '13 at 08:24