werer111
werer111

Reputation: 11

Delay download of .js file for last

My site requires one .js file for the site to work but uses another .js file for web analytics. Therefore, this last one is not really necessary so I would like the browser to load/download it after it has loaded/downloaded everything else: html markup, .css files and images. Is it possible ?

Upvotes: 1

Views: 1762

Answers (5)

ChristopheCVB
ChristopheCVB

Reputation: 7315

Try :

<head>
<script src="1"</script></head>
<body>
Your HTML here
<script src="2"></script>
</body>

Upvotes: 0

mrk
mrk

Reputation: 5117

Add DEFER to the script tag that you want to have loaded/executed last.

 <script DEFER src="....js"></script>

Upvotes: 2

Pezhvak IMV
Pezhvak IMV

Reputation:

Yes, try this:

<script language="javascript">
    window.onload = function(){
         var newScript = document.createElement("script");
         newScript.src = "address to your js";
         document.body.appendChild(newScript);
    }
</script>

Upvotes: 0

gorootde
gorootde

Reputation: 4073

Just a suggestion: Add an inline Javascript to your HTML file which waits for DOMReady event and than inserts the javascript tag for the second javascript lib into the head of your document.

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 77986

Yep:

<head>
...
</head>
<body>
.....
<script src="lastscript.js"></script>
</body>

Google also recommends a deferred JavasSript loading technique:

<script type="text/javascript">

 // Add a script element as a child of the body
 function downloadJSAtOnload() {
 var element = document.createElement("script");
 element.src = "deferredfunctions.js";
 document.body.appendChild(element);
 }

 // Check for browser support of event handling capability
 if (window.addEventListener)
 window.addEventListener("load", downloadJSAtOnload, false);
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;

</script>

Upvotes: 3

Related Questions