I have an older validation form which is depends on the prototype.js library.
Unfortunately I can't include a reference to the prototype.js library on the page. 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. 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.
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.
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.
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. Move any code that depends on the dynamically loaded script into the callback.