admin管理员组

文章数量:1305653

I am trying to optimize page loading time. And the only thing left is optimizing asset loading times. I have few assets and a library script. Some of the assets are dependent to this library.

Vendor Scripts

  • library.min.js
  • vendor.min.js

Bundle Scripts

  • page.bundle.js (dependent to library.min.js)
  • play.min.js (dependent to vendor.min.js)
  • gtm.min.js (dependent to library.min.js)

What I want to achieve is start loading all of these assets when page is fully loaded. As I am rendering everything at serverside, it is not a problem for me to delay user interactions. I just need to download library.min.js then page.bundle.js in the exact order but when I need to.

I tried few things, but I just couldn't start downloading and execute it in right order. Currently I am planning to use xhr and eval content when I need it. But I am not sure if this is the right way. There are more questions to ask when using this method. Caching etc.

Can someone give me an idea how can I split download and execution time of dynamically loaded javascript files?

I am trying to optimize page loading time. And the only thing left is optimizing asset loading times. I have few assets and a library script. Some of the assets are dependent to this library.

Vendor Scripts

  • library.min.js
  • vendor.min.js

Bundle Scripts

  • page.bundle.js (dependent to library.min.js)
  • play.min.js (dependent to vendor.min.js)
  • gtm.min.js (dependent to library.min.js)

What I want to achieve is start loading all of these assets when page is fully loaded. As I am rendering everything at serverside, it is not a problem for me to delay user interactions. I just need to download library.min.js then page.bundle.js in the exact order but when I need to.

I tried few things, but I just couldn't start downloading and execute it in right order. Currently I am planning to use xhr and eval content when I need it. But I am not sure if this is the right way. There are more questions to ask when using this method. Caching etc.

Can someone give me an idea how can I split download and execution time of dynamically loaded javascript files?

Share Improve this question edited Aug 29, 2018 at 16:00 Ahmet Can Güven asked Jul 9, 2018 at 6:37 Ahmet Can GüvenAhmet Can Güven 5,4624 gold badges42 silver badges61 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

You can dynamically create script elements and add it to the document body, set the src property to your javascript file and then let it download it. When the download finished, the promise will resolve and the next dependent js file will be set.

function setExternalScript(src) {
  return new Promise((resolve, reject) => {
       const scriptTag = document.createElement('script');
       scriptTag.type = 'text/javascript';
       scriptTag.src = src;
       scriptTag.onload = () => resolve();
       document.appendChild(document.body, scriptTag);
  });
}

async function afterLoaded() {
    const scripts = ['a.js','b.js','c.js'];
    for(let i=0; i< scripts.length; i++)
       await setExternalScripts(scripts[i]);
}

afterLoaded(); // run this whenever you need

What I want to achieve is start loading all of these assets when page is fully loaded.

Then just move these assets at the end of your page:

<body>
  Some cool content
  <script src="library.min.js"> </script>
  <script src="page.bundle.js"> </script>
</body>

I just need to run library.min.js then page.bundle.js in the exact order but when I need to.

Then put them in that order onto the page. You can also add the async and defer flag to defer the downloading. (Read on)

how can I split downloading and executing time of dynamically loaded javascript files?

For sure you can but why? If the js is downloaded, why not just run it directly?

Currently I am planning to use xhr and eval content when I need it.

In the very very rare case that you need to load additional javascript (e.g. a page with some minigames, were you load the game script when the user chooses one of them), just add the script to the body:

 function withScript(url, callback) {
   var script = document.createElement("script");
   script.src = url;
   script.onload = callback;
}

withScript("additional.js", function() {
  additional.start();
});

If you are using jquery with your project, then you can use get the script which is ajax callback. The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page. Its Success Callback is fired once the script has been loaded but not necessarily executed. You can find a working example https://www.w3schools./jquery/ajax_getscript.asp

For multiple script loading, you can use following code:

$.getMultiScripts = function(arr, path) {
var _arr = $.map(arr, function(scr, i) {
    var source = (path || "") + scr;
    updatePreloader(i, arr.length);
    return $.getScript(source);
});

_arr.push($.Deferred(function(deferred) {
    $(deferred.resolve);
}));

return $.when.apply($, _arr);
}

var prereqArray = [ "model/Lab.js", "controller/init/main.js" ];
function getEngineStarter(id) {

$.getMultiScripts(prereqArray, rPath).done(function() {
   console.log("Horray all loaded").

});

}

function setExternalScript(src) {
  return new Promise((resolve, reject) => {
       const scriptTag = document.createElement('script');
       scriptTag.type = 'text/javascript';
       scriptTag.src = src;
       scriptTag.onload = () => resolve();
       document.appendChild(document.body, scriptTag);
  });
}

async function afterLoaded() {
    const scripts = ['a.js','b.js','c.js'];
    for(let i=0; i< scripts.length; i++)
       await setExternalScripts(scripts[i]);
}

afterLoaded(); // run this whenever you need

本文标签: htmlDownload javascript dynamically and execute it laterStack Overflow