27
<html>
 <script>
    //some largeFunction()

    //load a script dynamically based on the previous code
    document.write("<script src='//...'><\/script>");
 </script>
</html>

Question: is it possible to move the largeFunction() out of the static html page and put it into a js file? If yes, how could I then call that function statically before writing the <script> tag?

6
  • 2
    Yes. You can. You can move entire function to a different file. Then load this file. About calling function you can have another script tag after this file to call it. You can also look into IIFE or window.onload. These can be in that file as well. Commented Feb 24, 2016 at 15:30
  • just need to put the script tag that load the js file before the one that create the new script tag Commented Feb 24, 2016 at 15:31
  • did you try that? to me it seems possible to make it work from separate file. it anyway have access to document object Commented Feb 24, 2016 at 15:31
  • Note! If this script deals with DOM element, make sure to load this file after entire HTML. or use window.onload to ensure elements to be manipulated are rendered Commented Feb 24, 2016 at 15:33
  • Is the optional/deferred loading a requirement? Commented Feb 24, 2016 at 15:33

4 Answers 4

36

Short answer: Yes.

As long as you load the first script containing the function first, you can call the function anywhere, as long as it's loaded first.

<script src="file1.js" type="text/javascript"></script> 
<script src="file2.js" type="text/javascript"></script> 

In this example, make sure file1.js contains your largeFunction() function. You can then call largeFunction(); inside file2.js.

You can also do this:

<script src="file1.js" type="text/javascript"></script> 
<script>
    largeFunction();
</script>

Just make sure your FIRST script contains the function.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to do the same with variables, i.e. loading a js file and then referring to a variable in that file in another script tag?
@User Definitely yep
11

You can try following options:


LargeFunction.js

function largeFunction(){
  // This is a global function and is a part of window object.
  // This can be called from anywhere once the file is loaded.
}

index.html

<script src="largeFunction.js" type="text/javascript"></script> 
<script>
    largeFunction();
</script>

IIFE

These are functions that are executed only once when the file is loaded. They are called the moment they are compiled.

function largeFunction(){
  
}

(function(){
  largeFunction();
})()

You can even try without IIFE

function largeFunction(){
  
}
largeFunction();

window.onload / $(document).ready()

This events are fired once all elements are rendered. If your JS is manipulating any elements like managing UI states or creating controls like datepickers or searchable dropdowns or adding options to select, these events are preferred.

Note: Both events are not same. You can refer following post window.onload vs $(document).ready()

// Pure JS
function largeFunction(){

}

window.onload = function(){
  largeFunction();
}


// jQuery
function largeFunction(){

}

$(document).ready(function(){
  largeFunction();
})

Note: Its not a good practice to have large function. You should also try to split function to multiple functions

function getData(callback){
  var data = ...
  // Gets data from server
  data = cleanData(data);
  data = processData(data);
  
  if(callback) callback(data); // callback refers to renderUI function
}

function cleanData(data){
  // Clean if any field needs formatting
  return data;
}

function processData(data){
  // You can permute logic to parse data
  return data;
}

function renderUI(data){
  // Update DOM element with data
}


function largeFunction(){
  getData(renderUI);
}

Comments

3

Without going into details about javascript modules, etc, I'll just address the easiest way for you to move forward and leave you to optimize as you see fit. Let's say you put largeFunction() into a separate file called myScript.js, then your HTML page setup would be like this:

<html>
 <script type="text/javascript" src="myScript.js"></script>
 <script>
    largeFunction();

    //load a script dynamically based on the previous code
    document.write("<script src='//...'><\/script>");
 </script>
</html>

As you can see, all you really need to do is make sure that you reference the external script file before your current script tag. From there, you can call largeFunction() as you would have if it were embedded in your HTML.

2 Comments

As a heads up, using document.write will apparently throw a warning or get blocked outright if you try to run a script on a device connected on a slower connection speed: developers.google.com/web/updates/2016/08/…
This answer is dead, but I agree and now I'd probably use require or include instead.
2

If you grab DOM elements and add event handlers in your JavaScript you don't have to put functions on the HTML page. You could just make the JS file and link to it using a script tag. It would probably be best to place the script tag at the bottom of the page to ensure that all of the DOM has loaded.

Example:

var getDomJquery = $("#got-Some-dom").on( "click", function(){
    // do some cool JS DOM stuff here
});


var getDomPureJs = document.getElementById("got-Some-dom").on( "click", function(){
    // do some cool JS DOM stuff here
});

In your HTML near bottom of the page.

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

2 Comments

But I want to initialize the stuff before rendering completed. Can I also execute a function in the myJsFile.js during load, without directly triggering the function?
Yes. you can do document.load( /////your code here. ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.