简体   繁体   English

从另一个 JS 文件加载带有 document.write 的库

[英]Loading library with document.write from another JS file

I have an older validation form which is depends on the prototype.js library.我有一个旧的验证表单,它依赖于prototype.js 库。

Unfortunately I can't include a reference to the prototype.js library on the page.不幸的是,我无法在页面上包含对prototype.js 库的引用。 I do not control that form's code.我不控制该表单的代码。

How would I approach the issue of loading this outside of editing the pages that need it?我将如何处理在编辑需要它的页面之外加载它的问题? That is, I need to load the library from another JavaScript library I do control.也就是说,我需要从其他JavaScript库中控制加载库。 Let me explain.让我解释。

Each page with the form has this include script:带有表单的每个页面都有这个包含脚本:

<script src="http://domain/validationScript.js"
    type="text/javascript"></script>

And inside the script I was thinking of doing something like this...在脚本中,我正在考虑做这样的事情......

document.write(unescape(
    "%3Cscript src='//ajax.googleapis.com/ajax/libs/prototype/1.6.1/prototype.js' type='text/javascript'%3E%3C/script%3E"
  ));

but it doesn't load prototype.js before the script.但它不会在脚本之前加载prototype.js

What am I doing wrong?我究竟做错了什么?


Ok, it's clear with the DOM sequence that it has a race condition where I can't use the loaded script in the script that's writing the include to the page.好的,很明显 DOM 序列存在竞争条件,我无法在将包含写入页面的脚本中使用加载的脚本。

But then how can I load the library from a script that itself needs to execute the code from the library it's loading?但是,如何从脚本加载库,该脚本本身需要从它正在加载的库中执行代码?

You are generating a new script element in the DOM, at the next point that one could be added.您正在 DOM 中生成一个新的脚本元素,在下一点可以添加。

This point is immediately after the current script element.该点紧跟在当前脚本元素之后。

Any code in the current script element can't use it, because it won't be loaded until the execution of the current element has finished.当前脚本元素中的任何代码都不能使用它,因为在当前元素的执行完成之前它不会被加载。

Since you are using jQuery you can use getScript() , which allows you to pass a callback method.由于您使用的是 jQuery,您可以使用getScript() ,它允许您传递回调方法。 Move any code that depends on the dynamically loaded script into the callback.将任何依赖于动态加载的脚本的代码移动到回调中。

You should add the script to the head of the dom:您应该将脚本添加到 dom 的头部:

var headID = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.1/prototype.js';
headID.appendChild(newScript);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM