- Tutorials / JavaScript / Tutorials
- Saturday, 12th Nov, 2016
Home » Tutorials » JavaScript » Inject External JavaScript & Detect When It Has Loaded
Injecting external JavaScript Library into a web page after page load is pretty simple for people who can write JavaScript, but it is NOT for marketers. I believe most of you guys heard about Google Tag Manager and what can you done with it.
Google Tag Manager allows marketers to add and update website tags – including conversion tracking, site analytics, remarketing, and more—with just a few clicks, without needing to involve in the web development process.
Unfortunately, some marketers or people without adequate knowledge of web development may face some problem when they’ve to inject third party JavaScript and send over the data to the third party service via Google Tag Manager.
Example, take a look on the following snippet:
<script> var script = document.createElement('script'); script.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'); script.setAttribute('type', 'text/javascript'); document.getElementsByTagName('head')[0].appendChild(script); $('#object').show(); </script>
Injecting external JavaScript after page load and start using the reference from the external JavaScript will cause a reference error, as the external JavaScript has not loaded yet:
To solve this issue, we’ve to detect when is the external JavaScript fully loaded:
var script = document.createElement('script'); script.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'); script.setAttribute('type', 'text/javascript'); document.getElementsByTagName('head')[0].appendChild(script); script.onload = function(){ $('#object').show(); }
The onload event fires immediately after the external JavaScript has been loaded, so you can use it to know when your external resources loaded.
Hope it helps!