Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically loading jQuery from hosted javascript file if not available on page
    primarykey
    data
    text
    <p>The idea of what I'm trying to do is allow a client to add a script that I host onto their website. I want to be able to use jQuery in my script but can not say for sure that it will always be available. Here is what I have code wise. This is the full file of my hosted javascript page so far and I can not get it to work. The $('title').html part is just so I can see if it works</p> <p><strong>I want the script that I am hosting to take care of including jQuery on the clients website. I do not want the client to have to include jQuery in addition to my script</strong></p> <pre><code>window.onload = function () { if (typeof jQuery == 'undefined') { var jq = document.createElement('script'); jq.type = 'text/javascript'; jq.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; var sc = document.getElementsByTagName('script')[0]; sc.parentNode.insertBefore(jq, sc); } console.log($('title').html()); } </code></pre> <p>This javascript file is loacated on my server and my client would include this file in much of the same way that you would for google analytics.</p> <p>This is the only thing that I want my client to have to include. Pulled basically the same as google analytics</p> <pre><code>&lt;script type="text/javascript"&gt; var _waq = _gaq || []; _waq.push(['PARAM1', 'PARAM2']); (function() { var wa = document.createElement('script'); wa.type = 'text/javascript'; wa.async = true; wa.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'PATH/TO/SCRIPT/wa.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wa, s); })(); &lt;/script&gt; </code></pre> <p>When I run the page I get an error saying <code>Uncaught ReferenceError: $ is not defined</code> however if I then right after the page loads, i type in <code>$('title').html();</code> I get the title returned in the console.</p> <p>Im sure this has something to do with timing of when the console.log in the script is running and has not let jQuery fully load yet. My question is how am I able to create a javascript page that a client can add that dynamically loads jquery if it is not available, and have it loaded before any of the other stuff on the script runs? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload