问题描述
考虑这个Coffeescript类,在每个类都存在于自己的文件中的应用程序中。
类管理器扩展人
title:[[manager]]
如果该文件在titles ,生成错误。我假设这是因为Coffeescripts安全包装是执行.call(this),当这个文件第一次加载?
否则,如果我延迟运行任何代码,直到整个页面完全加载($(document.ready()),我可以确保所有的javascript文件在任何代码实际运行之前完全加载。
$ b $
这可能会导致一些恼人的加载顺序问题,
$ b
如果 titles
在另一个文件中定义,则 class Manager
的范围没有影响,这是一个订单问题。 titles
如何定义?
当第一个JS文件运行时,DOM可能已经被初始化! (实际上,如果浏览器将网页的HTML缓存,则会发生这种情况。)
因此,保持简单。只需按正确的顺序加载脚本即可。请记住,出于所有实际目的,您的脚本将由浏览器按顺序连接到一个JS文件中。
Consider this Coffeescript class, in an app where each class lives in its own file.
class Manager extends Person
title: titles["manager"]
If that file is loaded before the "titles" object, an error generated. I'm assuming this is because of Coffeescripts safety wrapper which is performing ".call(this)" when this file is first loaded?
Otherwise, if I were to delay running any code until after the entire page had fully loaded ($(document.ready()), I could be sure that all the javascript files were fully loaded before any code actually ran.
Doesn't this create some annoying load order problems, or am I not doing something correctly?
It can't be both an order issue and a wrapper issue. Wrapping something with a function that's run immediately has no effect on order, only on scope.
And if titles
is defined in another file, then the scoping of class Manager
doesn't matter. So, it's an order issue. How is titles
defined?
Not quite. $(document).ready()
(note the parentheses—there is no document.ready
function...) delays a function's execution until all of the page's HTML has been loaded, which doesn't mean all JavaScript has been loaded. Here's the good news: From the standpoint of JavaScript code, it doesn't matter whether other JavaScript files have been loaded, because they're all run in order. (Note: I'm assuming here that you're not doing anything fancy like adding additional <script>
tags from your JavaScript code.) So as long as you have
<script src="titles.js"></script>
<script src="Manager.js"></script>
you can rest assured that Manager.js
will only run after titles.js
has.
Warning! Relying on $(document).ready()
for ordering JS code is a common mistake that can lead to confusion! If your HTML looked like this
<script src="Manager.js"></script>
<script src="titles.js"></script>
where titles.js
creates a global called titles
and Manager.js
looks like this
$(document).ready ->
console.log titles
then the output will sometimes be titles
, and sometimes be undefined
. Why? Because as the docs say,
And the DOM may already have been initialized when the first JS file is run! (In practice, this will tend to happen if the browser has the page's HTML cached.)
So, keep it simple. Just load your scripts in the right order. Remember that, for all practical purposes, your scripts are concatenated together by the browser, in order, into a single JS file.
这篇关于Coffeescript,Backbone和加载顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!