So if I have the following:
<script type="text/javascript" src="offsite file I am referencing"></script>
and I simply want to delay the execution of calling that file using settimeout, how would I go about that?
Very strange in that I would have no problem using settimeout on a simple function, but I am kind of stumped in this seemingly more simple situation.
My thought would be I could just make a function that calls that file after x amount of time, but calling the file in the function seems to be escaping me.
If you cannot do that for some reason, then you can delay the loading of the external script file like this: setTimeout(function() { var headID = document. getElementsByTagName("head")[0]; var newScript = document. createElement('script'); newScript.
You should delay JS files so that none of them will be loaded until user interaction. It means that as long as no user clicks on a button or scrolls a page's content, the browser will not execute any JS scripts. You should also remove unused JS files.
defer. This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded . Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).
you are almost there.
in your settimeout callback function do the following:
var script = document.createElement('script'); script.src = "http://whatever.com/the/script.js"; document.getElementsByTagName('head')[0].appendChild(script);
The simplest way would be to let the script file load normally and just call a main function in it with setTimeout()
like this:
<script type="text/javascript" src="offsite file I am referencing"></script> <script type="text/javascript"> setTimeout(executeMainFunction, 5000); // function in offsite js file </script>
If you cannot do that for some reason, then you can delay the loading of the external script file like this:
setTimeout(function() { var headID = document.getElementsByTagName("head")[0]; var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = 'http://www.somedomain.com/somescript.js'; headID.appendChild(newScript); }, 5000);
Here's a reference article on dynamic loading of script files (and other types of resources): http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With