fetchInject([ 'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js' ]).then(() => { console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`) })
jQuery加载
使用jQuery的$.getScript方法加载脚本:
1 2 3
$.getScript("my_lovely_script.js", function() { alert("Script loaded but not necessarily executed."); });
动态脚本加载
在HTML中动态添加脚本标签:
1 2 3 4 5
functiondynamicallyLoadScript(url) { var script = document.createElement("script"); // create a script DOM node script.src = url; // set its src to the provided URL document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead) }
functionloadScript(url, callback) { // Adding the script tag to the head as suggested before var head = document.head; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url;
// Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = callback; script.onload = callback;
// Fire the loading head.appendChild(script); }
var myPrettyCode = function() { // Here, do whatever you want };
define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) { //Your actual script goes here. //The dependent scripts will be fetched if necessary.
return libraryObject; //For example, jQuery object });
implementation.js文件:
1 2 3 4 5
require(['some-dependency'], function(dependency) { //Your script goes here //some-dependency.js is fetched. //Then your script is executed });