JavaScript加载顺序
我同时使用amq.js(ActiveMQ)和Google Maps。我按此顺序加载脚本
<head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title>AMQ & Maps Demo</title> <!-- Stylesheet --> <link rel="stylesheet" type="text/css" href="style.css"></link> <!-- Google APIs --> <script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"></script> <!-- Active MQ --> <script type="text/javascript" src="amq/amq.js"></script> <script type="text/javascript">amq.uri='amq';</script> <!-- Application --> <script type="text/javascript" src="application.js"></script> </head>
但是在我的application.js中,它可以正常加载Maps,但是尝试通过AMQ订阅主题时出现错误。 AMQ取决于原型,而Firefox中的错误控制台表示未定义对象。我认为在脚本加载完成之前使用amq对象存在问题。有没有一种方法可以确保在我的application.js中使用它们之前先加载两个脚本?
Google有一个很好的函数调用google.setOnLoadCallback(initialize);,效果很好。我不确定amq.js是否有这样的内容。
解决方案
回答
Is there a way to make sure both scripts load before I use them?
是的。
将我们要最后加载的代码(application.js内容)放入原型的document.observe中。这应该确保仅在原型+其他内容完成并准备好之后才能加载代码。 (如果我们熟悉jQuery,则此功能类似于jQuery的$ {document).ready
)
回答
在jQuery中,我们可以使用:
$(document).ready(function(){/*do stuff here*/});
在执行操作之前,请确保已加载javascript并且dom已准备就绪。
在原型中,这似乎可以工作
document.observe("dom:loaded", function() {/*do stuff here*/});
如果我正确理解了问题,我认为这可能会有所帮助。
如果我们不想依靠lib来执行此操作...我认为这可能有效:
<script> function doIt() {/*do stuff here*/} </script> <body onLoad="doIt();"></body>
回答
AMQ depends on prototype which the error console in FireFox says object is not defined.
我们是说AMQ依赖于原型库吗?在我们提供的代码中看不到该库的导入。
回答
Is there a way to make sure both scripts load before I use them in my application.js?
JavaScript文件应顺序加载并阻止,因此除非我们所依赖的脚本执行了异常操作,否则我们需要做的就是在其他文件之后加载application.js。
非阻塞JavaScript下载提供了有关脚本加载方式的一些信息(并讨论了一些破坏阻塞的技术)。
回答
Do you mean that AMQ depends on the Prototype library? I can't see an import for that library in the code you've provided.
是的,对于ActiveMQ的javascript(amq.js)确实取决于Prototype。在amq.js中,它加载了3个脚本_amq.js,behaviour.js和prototype.js。
感谢我们对JavaScript加载顺序wrumsby的帮助。这告诉我我的虫子在另一座城堡里:(
我想我有一个不同的问题。我还检查了从ActiveMQ 5.0到5.1的js文件,发现它们也一样。从5.0到5.1的某些更改都需要刷新主题才能订阅。我会继续寻找,但感谢我们消除了这种可能的原因。
回答
我有一个类似的问题,只有一个脚本。我想出的解决方案是对使用document.createElement('script')创建的script对象使用addEventListener(" load",fn,false)`这是加载任何标准JS文件的最终函数。并允许我们添加"加载后"脚本。
function addJavaScript( js, onload ) { var head, ref; head = document.getElementsByTagName('head')[0]; if (!head) { return; } script = document.createElement('script'); script.type = 'text/javascript'; script.src = js; script.addEventListener( "load", onload, false ); head.appendChild(script); }
我希望这会在将来对某人有所帮助。