That's not working because your $(document).ready(...
line runs before jQuery loads, and so it fails because either $
is undefined (throwing a ReferenceError
) or it refers to something other than jQuery. Also, you're calling jQuery.noConflict()
before jQuery is loaded, and if that call did work, it would mean that $
no longer referred to jQuery at all, so $(document).ready(...
still wouldn't work.
In any modern browser, you can use the load
event on the script
element you're adding, which tells you that the script has been loaded. Probably best to pass a callback into a call you make to includejquery.js
, like this:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
includejQuery(function($){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js
:
function includejQuery(callback) {
if(window.jQuery)
{
// jQuery is already loaded, set up an asynchronous call
// to the callback if any
if (callback)
{
setTimeout(function() {
callback(jQuery);
}, 0);
}
}
else
{
// jQuery not loaded, load it and when it loads call
// noConflict and the callback (if any).
var script = document.createElement('script');
script.onload = function() {
jQuery.noConflict();
if (callback) {
callback(jQuery);
}
};
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
}
Changes there:
In includejquery.js
, just define a function and wait to be called.
Have that function accept a callback.
Have it wait for the script to load.
When the script is loaded, call jQuery.noConflict
and then, if there's a callback, call it and pass in the jQuery
function.
In the HTML, I'm calling the function, and receiving the argument it passes me as $
, so within that function only, $ === jQuery
even though outside it, it doesn't (because of noConflict
).