当前位置:首页> 正文

关于Google Maps:JavaScript加载顺序

关于Google Maps:JavaScript加载顺序

JavaScript Load Order

我同时使用amq.js(ActiveMQ)和Google Maps。 我按此顺序加载脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    AMQ & Maps Demo

    <!-- 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">

    <!-- Active MQ -->
    <script type="text/javascript" src="amq/amq.js">
    <script type="text/javascript">amq.uri='amq';

    <!-- Application -->
    <script type="text/javascript" src="application.js">
</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 in my application.js?

JavaScript文件应按顺序加载并阻止,因此除非您所依赖的脚本执行异常操作,否则您需要做的就是在其他文件之后加载application.js。

非阻塞JavaScript下载提供了有关脚本加载方式的一些信息(并讨论了一些破坏阻塞的技术)。


在jQuery中,您可以使用:

1
$(document).ready(function(){/*do stuff here*/});

在执行操作之前,请确保已加载javascript并且dom已准备就绪。

在原型中,这似乎可以工作

1
document.observe("dom:loaded", function() {/*do stuff here*/});

如果我正确理解了您的问题,我认为这可能会有所帮助。

如果您不想依靠lib来执行此操作...我认为这可能有效:

1
2
3
   function doIt() {/*do stuff here*/}

<body onloadx="doIt();"></body>

我有一个类似的问题,只有一个脚本。我想出的解决方案是将addEventListener("load",fn,false)用于使用document.createElement('script')创建的script对象。这是最后的函数,该函数可以加载任何标准JS文件,并允许您添加"后加载"脚本。

1
2
3
4
5
6
7
8
9
10
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);
}

我希望这会在将来对某人有所帮助。


Is there a way to make sure both scripts load before I use them?

是。

将您要最后加载的代码(您的application.js内容)放入原型的document.observe。这应该确保仅在原型+其他内容完成并准备好之后才能加载代码。 (如果您熟悉jQuery,则此功能类似于jQuery的$(document).ready)


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的某些更改都需要刷新主题才能订阅。我会继续寻找,但感谢您消除了这种可能的原因。


AMQ depends on prototype which the error console in FireFox says object is not defined.

您是说AMQ依赖于原型库吗?您提供的代码中看不到该库的导入。


您还可以使用内置的SharePoint javascript方法来控制脚本的执行。

1
_spBodyOnLoadFunctionNames.push("yourFunction");


展开全文阅读

相关内容