...

View Full Version : Injecting jQuery



tangibleLime
03-18-2012, 05:03 AM
I need to be able to inject the jQuery library into a page through a JavaScript file, then be able to immediately use those jQuery functions.

My code to injecting jQuery works:

jq = document.createElement("script");
jq.setAttribute("type","text/javascript");
jq.setAttribute("src","jquery.js");
document.getElementsByTagName('head')[0].appendChild(jq);


After this code runs, I can do something such as "on a button click, do $(...).slideUp(...), but I cannot run $(...).slideUp(...) directly after that code.

In my test HTML file, I have this in the head:

<script type="text/javascript">
injectJQuery();
$("#test").slideUp(1000);
</script>


Where injectJQuery(); is the code above that injects the jQuery. When the browser hits the "$("#test").slideUp(1000);" line, it tells me $ is undefined which means jQuery is not loaded.

How would I go about doing this?

devnull69
03-18-2012, 09:43 AM
Why don't you just add a <script> tag in the head? It would automatically deal with loading the script and continue only when the script has been loaded.

Nevertheless there is a "load" event triggered when an injected script has been loaded.

Furthermore, the element "#test" will not be available in the head section because it will only be loaded and embedded into the DOM after processing the body section. So either put the <script> to the end of the body section, or add $(document).ready() to your code.

Try this



function injectJQuery(callback) {
jq = document.createElement("script");
jq.setAttribute("type","text/javascript");
jq.setAttribute("src","jquery.js");

jq.onload = callback;

document.getElementsByTagName('head')[0].appendChild(jq);
}

injectJQuery(function() {
$(document).ready(function() {
$("#test").slideUp(1000);
});
});



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum