Skip to content Skip to sidebar Skip to footer

Inclusion Of A Js File In Html

I am include a huge javascript file(500K) in my HTML. Is there a smart way to know if it has been loaded. One way I can think of is to have a variable in its constructor to initial

Solution 1:

By using jQuery you can handle a callback function that runs when the script file is loaded:

$.getScript("yourScriptFile.js", function(){
  // What to do when the script is loaded
});

Docs

Solution 2:

As an clarification on Oscar's answer:

<scripttype='text/javascript'src='script.js'></script><scripttype='text/javascript'>alert('the file has loaded!'); 
 //Anything here will not be executed before the script.js was loaded</script>

Also if the file is huge, it might be better to load it after the page has loaded, so that you, on slow connections can use the page before it's loaded:

<head>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
 Nothing here will be rendered until the script has finished loading
</body>

Better is to:

<head>
</head>
<body>
 I will be rendered immidiatly
</body>
<script type='text/javascript' src='script.js'></script>
</html>

That way users get the page fast and only then have to wait for the javascript functionality.

Solution 3:

Have you tried compressing the javascript file? Moving some of the functions into separate Javascript files, and only including the needed javascript?

Solution 4:

You could call a function at the end of the script file which would inform the script on the page that it's ready for use.

Post a Comment for "Inclusion Of A Js File In Html"