I’m creating a jquery plugin and I want to verify an external script is loaded. This is for an internal web app and I can keep the script name/location consistent(mysscript.js). This is also an ajaxy plugin that can be called on many times on the page.
If I can verify the script is not loaded I’ll load it using:
jQuery.getScript()
How can I verify the script is loaded because I don’t want the same script loaded on the page more than once? Is this something that I shouldn’t need to worry about due to caching of the script?
Update: I may not have control over who uses this plugin in our organization and may not be able to enforce that the script is not already on the page with or without a specific ID, but the script name will always be in the same place with the same name. I’m hoping I can use the name of the script to verify it’s actually loaded.
Advertisement
Answer
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) —
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') { //the flag was not found, so the code has not run $.getScript('<external JS>'); }
Update
You can check for the existence of the <script>
tag in question by selecting all of the <script>
elements and checking their src
attributes:
//get the number of `<script>` elements that have the correct `src` attribute var len = $('script').filter(function () { return ($(this).attr('src') == '<external JS>'); }).length; //if there are no scripts that match, the load it if (len === 0) { $.getScript('<external JS>'); }
Or you can just bake this .filter()
functionality right into the selector:
var len = $('script[src="<external JS>"]').length;