Comment inclure un fichier JavaScript dans un autre fichier JavaScript

Mots clés : javascriptfileimportincludejavascript

meilleur 5 Réponses Comment inclure un fichier JavaScript dans un autre fichier JavaScript

vote vote

90

{     "type": "module" } 
export function hello() {   return "Hello"; } 
import { hello } from './module.js'; let val = hello();  // val is "Hello"; 
export function hello() {   return "Hello"; } 
import { hello } from './module.mjs'; let val = hello();  // val is "Hello"; 
<script type="module">   import { hello } from './hello.mjs'; // Or it could be simply `hello.js`   hello('world'); </script> 
// hello.mjs -- or it could be simply `hello.js` export function hello(text) {   const div = document.createElement('div');   div.textContent = `Hello ${text}`;   document.body.appendChild(div); } 
<script type="module">   import('hello.mjs').then(module => {       module.hello('world');     }); </script> 
// mymodule.js module.exports = {    hello: function() {       return "Hello";    } } 
// server.js const myModule = require('./mymodule'); let val = myModule.hello(); // val is "Hello"    
fetchInject([   'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js' ]).then(() => {   console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`) }) 
$.getScript("my_lovely_script.js", function() {    alert("Script loaded but not necessarily executed."); }); 
function dynamicallyLoadScript(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) } 
var js = document.createElement("script");  js.type = "text/javascript"; js.src = jsFilePath;  document.body.appendChild(js);  var s = new MySuperObject();  Error : MySuperObject is undefined 
function loadScript(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 }; 
loadScript("my_lovely_script.js", myPrettyCode); 
vote vote

81

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 }); 
require(['some-dependency'], function(dependency) {      //Your script goes here     //some-dependency.js is fetched.        //Then your script is executed }); 
vote vote

70

$("head").append($("<script></script>").attr("src", url));  /* Note that following line of code is incorrect because it doesn't escape the  * HTML attribute src correctly and will fail if `url` contains special characters:  * $("head").append('<script src="' + url + '"></script>');  */ 
(function($) {     /*      * $.import_js() helper (for JavaScript importing within JavaScript code).      */     var import_js_imported = [];          $.extend(true,     {         import_js : function(script)         {             var found = false;             for (var i = 0; i < import_js_imported.length; i++)                 if (import_js_imported[i] == script) {                     found = true;                     break;                 }                          if (found == false) {                 $("head").append($('<script></script').attr('src', script));                 import_js_imported.push(script);             }         }     });      })(jQuery); 
$.import_js('/path_to_project/scripts/somefunctions.js'); 
function hello() {     alert("Hello world!"); } 
vote vote

64

function require(script) {     $.ajax({         url: script,         dataType: "script",         async: false,           // <-- This is the key         success: function () {             // all good...         },         error: function () {             throw new Error("Could not load script " + script);         }     }); } 
require("/scripts/subscript.js"); 
subscript.doSomethingCool();  
vote vote

55

function includeJs(jsFilePath) {     var js = document.createElement("script");      js.type = "text/javascript";     js.src = jsFilePath;      document.body.appendChild(js); }  includeJs("/path/to/some/file.js"); 

Questions similaires