Reputation: 20952
I have one JS file in the header (this is for Google DFP) and another before the </body>
I have found if the header JS file doesn't load before the bottom one I get this error in Chrome Console:
Uncaught TypeError: Object #<Object> has no method 'defineSlot'
The defineSlot is defined in the first script. This issue only occurs on around every 10 page refresh so most of the time its ok.
I want advise on how to deal with this issue. Below are the 2 scripts:
Header Script:
<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>
<script type='text/javascript'>
googletag.cmd.push(function() {
googletag.pubads().enableAsyncRendering();
slot1 = googletag.defineSlot('/21848415/GoneGlobal_Square', [250, 250], 'doubleClickSquareIndex-250-250').addService(googletag.pubads());
slot2 = googletag.defineSlot('/21848415/GoneGlobal_Skyscraper', [160, 600], 'doubleClickSkyscraperIndex-160-600').addService(googletag.pubads());
slot3 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardIndex-728-90').addService(googletag.pubads());
slot4 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardHeaderInternal-728-90').addService(googletag.pubads());
slot5 = googletag.defineSlot('/21848415/GoneGlobal_SmallSquare', [200, 200], 'doubleClickSmallSquareHeaderExternal-200-200').addService(googletag.pubads());
googletag.enableServices();
});
</script>
Below is the second script - this is only part of it (its quite long):
$(function() {
///////////////////////// Double Click AD Variables
var slot1 = googletag.defineSlot('/21848415/GoneGlobal_Square', [250, 250], 'doubleClickSquareIndex-250-250');
var slot2 = googletag.defineSlot('/21848415/GoneGlobal_Skyscraper', [160, 600], 'doubleClickSkyscraperIndex-160-600');
var slot3 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardIndex-728-90');
var slot4 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardHeaderInternal-728-90');
var slot5 = googletag.defineSlot('/21848415/GoneGlobal_SmallSquare', [200, 200], 'doubleClickSmallSquareHeaderExternal-200-200');
)};
Is there a way to stop a script running another another method/function is loaded?
Can I create some sort of dependency?
How can I ensure the top JS is loaded before the bottom?
Upvotes: 4
Views: 7722
Reputation: 10900
The other solutions here might work but the real issue is to do with the way you are using DFP.
DFP is loaded asynchronously so the method defineSlot will not exist on your page at the time the script that is causing the error is executed.
All of your DFP code should be contained within the googletag.cmd.push
wrapper which will store commands until DFP is loaded and then execute them in the correct order.
Simply wrapping any DFP code like so, should fix your errors:
googletag.cmd.push(function() {
// Double Click AD Variables
});
Upvotes: 6
Reputation: 95588
Store your scripts in separate files. Then something like the following should work:
function loadScript(pathToScript, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = pathToScript + "?t=" + new Date().getTime(); //prevent caching
if (callback) {
script.onload = callback;
}
head.appendChild(script);
}
The loadScript
function loads a script that resides at "pathToScript" and once it has finished loading the script, it calls the provided callback. You need a callback because loading an external resource is an asynchronous operation. Which means that you basically need a "notification" when it has finished loading the external resource. This is basically what a callback does. If you depend on data that comes from an asynchronous operation, you cannot fire off the operation and then go ahead and try to use the data or resource because the data will not have finished loading. So any code that depends on the resource, you put inside the callback. Why we're doing this will be clearer later on.
var scripts = ["/path/to/first/script.js", "/path/to/second/script.js"];
function load(i) {
if (i < scripts.length) {
loadScript(scripts[i], function () {
load(++i);
});
} else {
//all your scripts have loaded, so go ahead and do what you need to do
}
}
load(0);
The scripts
array contains an array of scripts to load. The order is implied by the position of the script in the array. So a script that is at scripts[0]
will be loaded before a script at scripts[1]
.
The load
function is what ensures that you're loading your scripts in the desired order. We know that the loading operation is asynchronous. We also know that a callback will be called once the operation is done. Using that information, we can load the second script after the first script finishes loading. There is one argument to load
, which represents the current index of the scripts
array. We set the index i
initially to 0
, which means that we're going to load the script at index 0
first. We then look at the value of i
. If it is lesser than the length of the array it means that we're not done going through all the scripts (think of it as a loop). So if i
is lower than the length, we call the loadScript
function with the value of scripts[i]
. Then in our callback, we call our load
function again but this time we increment the current value of i
. So when the script has finished loading, we end up calling load
with the incremented index and so we can now load our next script.
If i
is equal to scripts.length
, it means that we have loaded all our scripts and so we will go into the else
block, and this is where you put the code that you need to run after all scripts have been loaded.
The final line is the actual call to load
, with the argument 0
, which starts the whole process by starting with the path to the first script, which is at index 0
of the scripts
array.
You can rewrite the load
function as an IIFE as well, if you wish:
(function load(i) {
if (i < resources.length) {
loadResource(resources[i], function () {
load(++i);
});
}
})(0);
Here you have a "self-invoked" function that calls itself in the callback. It is functionally equivalent to the less-exotic version above.
Upvotes: 4
Reputation: 2623
you can create your own event lets say first_script_loaded
and when the first script is loaded you can add at the end $(document).trigger("first_script_loaded")
, you might also want to set a global boolean
just for this, where it is set to false
in the beginning, and when the 1st script is loaded, you set it to true
in the second script, check if the boolean
is true
, which means the 1st script has already been loaded before starting to load the second script, but if it is false, then listen to the event $(document).on("first_script_loaded")
and add your code in the callback
of the on
method.
Upvotes: 0