2

I am investigating a way to include a JavaScript file within some script tags. I have a large JavaScript file of Google Analytics Tracking Code and I need to include it at a certain point in my code. This is my code below:

<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789']);
<script type="text/javascript" src="/scripts/search_engines.js"></script>
_gaq.push(['_trackPageview']);
</script>

I need to have search_engines.js before the _trackPageview, but the syntax is clearly invalid.

search_engines.js has 290 lines of this:

_gaq.push(
['_addOrganic','advancedsearch2.virginmedia.com','SearchQuery',true],
['_addOrganic','alltheweb','q',true],
['_addOrganic','ananzi','qt',true],

I was looking a jQuery's addScript, but that doesn't appear to offer what i'm looking for.

Is there a way to include the JavaScript file within my script tags?

1
  • Inside search_engines.js you can fire event and attach observer to it from anywhere. Commented Aug 20, 2012 at 9:38

2 Answers 2

3

Load your script over AJAX and run the dependent code in a callback. This is trivial with jQuery:

$.getScript('/scripts/search_engines.js').done(function() {
    _gaq.push(['_trackPageview']);
});

Or, just put the whole GA code in one JS include.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so does this effectively include the file when getScript is called? The _trackPageview call is obviously more important the including the file, so I wouldn't want there to be any occasion where the _trackPageview doesn't fire.
Yes - the script is loaded and immediately executed at this point. The done callback fires only if the JS include loads successfully. If you want to ensure this runs regardless of whether the JS include loads successfully, change done to complete
0

Or you can use like this :

<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456789']);
</script>
<script type="text/javascript">
  document.write(unescape(%3Cscript type="text/javascript" src="/scripts/search_engines.js"%3E%3C/script%3E)); 
</script>
<script type="text/javascript">
  _gaq.push(['_trackPageview']);
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.