Putting JavaScript code in a separate file does not work

五迷三道 提交于 2020-01-31 19:12:25

问题


I am working with Optimizely guiders.js example code:

http://jeffpickhardt.com/guiders/

Though if I extract the JavaScript code and place it in a separate file, the guiders do not load.

Here is the edited HTML:

<html>
  <head>

    <!-- guider.js requires jQuery as a prerequisite. Be sure to load guider.js AFTER jQuery. -->
    <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
    <script type="text/javascript" src="guider.js"></script>
    <script type="text/javascript" src="guidedTour.js"></script>

    <link rel="stylesheet" href="guider.css" type="text/css" />
  </head>
  <body>
    <span id="clock" style="border: 2px solid #333; width: 300px; height: 200px; text-align: center;" onclick="guider.next();">
      <br />
      <img src="clock.gif" width=150 height=150 />
    </span>


  </body>
</html>

I have all the JavaScript code in guidedTour.js, in the same directory. All .js files are also in same directory. And the code worked before extracting it in separate file.

The guiders do not load when JavaScript is in separate file.

I am getting the following error in Chrome:

"Uncaught TypeError: Cannot read property 'clientHeight' of null jquery-1.5.1.min.js:16"

Trying a more recent version of jQuery throws an error on guiders.js. Anyway it seems a different behavior than if I keep the JavaScript code in the index.html.


I have created a jsfiddle for the working code: http://jsfiddle.net/vpMQy/

I do not know how to create a similar jsfiddle with the JavaScript in a separate file so that I can reproduce the problem.

Is it possible to put this JavaScript code in a separate file?


回答1:


Always wrap your code inside the DOM ready handler

$(document).ready(function() {
    //your code here
});

Or its shorthand

$(function() {
    //your code here
});

Or put your scripts at the very end of the document's body:

    //...
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="myScript.js"></script>
 </body>

And you won't have problems manipulating them DOM before it's ready. =]



来源:https://stackoverflow.com/questions/11938439/putting-javascript-code-in-a-separate-file-does-not-work

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