This is probably not possible but worth asking. I am dynamically inserting script tags into my head section of my page. At the moment I am using document.write which many of you will frown upon, but it does do the job fine.
However, for the reasons outlined here, I would like to find an alternative to document.write.
Therefore, I need a function that will do this:
<!-- The document.write writes the new script here synchronously so it will block other scripts -->
<script type="text/javascript">
// Code here that uses the code from the dynamically inserted script
</script>
Can anybody suggest anything with jQuery or plain javascript that will insert an element on the page, but also meets these requirements:
- Places the element at the point of which the function was called. e.g. the script tag gets placed after the script tag that called it
- The script gets loaded synchronously and therefore blocks the other scripts until it is complete
Google do this with their Google.load() method, do they use document.write? Surely not…
You can look at this article – http://www.phpied.com/non-onload-blocking-async-js/
Similar script is used by facebook for loading their SDK asynchronously.
It’s cross-browser and can load scripts asynchronously even when the html on the page is not valid (even if the head/body tag are missing).
Here is an example directly from the facebook’s SDK:
You have to make some modifications because it allows you to load the script just a single time (because of
if (d.getElementById(id)) {return;}).If we look at the script closer we can see a number of benefits:
scripttag (because of the script for async loading) so that’s why it’s getting the first script elementsrc