JD06
JD06

Reputation: 191

How can I change my script order when the HTML cannot be modified?

Current:

<head>
<script src="Custom.JS">
<script src="jQuery.JS">
</head>

Need:

<head>
<script src="jQuery.JS">
<script src="Custom.JS">
</head>

I can't edit the document, but I can edit the script files. Any way to do this?

Upvotes: 1

Views: 134

Answers (3)

user2864740
user2864740

Reputation: 61905

This is a bad scenario and the root cause should be fixed, however.. there are some "approaches".

Here is one that I am presenting. It assumes that jQuery.js cannot (and should not) be modified and should still contain all the relevant jQuery code, but Custom.js is fair-game and the code it runs can be treated asynchronously.

Consider if Custom.js looks like so (modify/fix as required):

(function (fn) {
   if (window.jQuery) {
      // jQuery already loaded, don't reload/reevaluate it
      fn(window.jQuery);
   } else {
      // Use of document.write because document.head is not supported before IE9.
      // (If IE9+ was the minimum version I would recommend doing the script
      //  insertions via DOM and using onload, as these would be available then.)
      window.__CustomJs_OnLoad = function () {
          // This now runs after jQuery is loaded (from the injected script)
          del window.__CustomJs_OnLoad;
          fn(window.jQuery);
      };
      // Script.onload could be used IE8+, but why not go all-the-way awesome?
      // These scripts are guaranteed to run synchronously in document-order.
      document.write("<script src=jQuery.js></sc" + "ript>");
      document.write("<script>__CustomJs_OnLoad()</sc" + "ript>");
   }
}(function ($) {
    // The rest of Custom.js here - which should already be nicely wrapped
    // in a function/module anyway, no?
}));

Upvotes: 2

guest271314
guest271314

Reputation: 1

Try

<head>
<script src="jQuery.JS">
</head>

js

$.holdReady(true);
$.getScript("Custom.JS", function(script) {
  $.holdReady(false);
})
$(document).ready(function) {
  // do stuff
});

Upvotes: 0

markasoftware
markasoftware

Reputation: 12662

You can have enclose the entire body of custom.js in a function and then edit jQuery.js so that when it's done with its work it calls that function in custom.js, effectively switching their execution order.

Or, If you don't have control over jQuery.js, you can just copy and paste it's contents into the to of custom.js. That easy you'll have access to the jQuery functions, and when the jQuery.js file loads, it'll still be ok (it'll just redefine everything)

Upvotes: 0

Related Questions